Tag Archives: matlab
Can the number of points in current function in Matlab Antenna Toolbox be manually assigned?
I’ve defined a half-wavelength antenna, and I use the current function in Matlab Antenna Toolbox to get the value of the current over the entire antenna, which is discrete point by point. I found that the current function in Matlab Antenna Toolbox can divide the antenna into several points with different densities according to the physical meaning of the antenna, but I don’t know the inner method of this division. Then I change the position of the feedpoint in this dipole. Each time I change the position of the feedpoint, the number of points divided by the current function changes. But I want to store the current value of each feedpoint in a matrix, so I want the number of points can be manually determined. However, I did not find such an operation in Matlab. I could only change the mesh size of maxEdgeLength, but I could not determine the number of points. Is there a similar operation in Matlab?
ant = dipole(‘Length’, L, ‘Width’, 10e-4*L); % Define length and width
maxEdgeLength = L / 60;
mesh(ant, ‘MaxEdgeLength’, maxEdgeLength);
[currentData, points] = current(ant, f);I’ve defined a half-wavelength antenna, and I use the current function in Matlab Antenna Toolbox to get the value of the current over the entire antenna, which is discrete point by point. I found that the current function in Matlab Antenna Toolbox can divide the antenna into several points with different densities according to the physical meaning of the antenna, but I don’t know the inner method of this division. Then I change the position of the feedpoint in this dipole. Each time I change the position of the feedpoint, the number of points divided by the current function changes. But I want to store the current value of each feedpoint in a matrix, so I want the number of points can be manually determined. However, I did not find such an operation in Matlab. I could only change the mesh size of maxEdgeLength, but I could not determine the number of points. Is there a similar operation in Matlab?
ant = dipole(‘Length’, L, ‘Width’, 10e-4*L); % Define length and width
maxEdgeLength = L / 60;
mesh(ant, ‘MaxEdgeLength’, maxEdgeLength);
[currentData, points] = current(ant, f); I’ve defined a half-wavelength antenna, and I use the current function in Matlab Antenna Toolbox to get the value of the current over the entire antenna, which is discrete point by point. I found that the current function in Matlab Antenna Toolbox can divide the antenna into several points with different densities according to the physical meaning of the antenna, but I don’t know the inner method of this division. Then I change the position of the feedpoint in this dipole. Each time I change the position of the feedpoint, the number of points divided by the current function changes. But I want to store the current value of each feedpoint in a matrix, so I want the number of points can be manually determined. However, I did not find such an operation in Matlab. I could only change the mesh size of maxEdgeLength, but I could not determine the number of points. Is there a similar operation in Matlab?
ant = dipole(‘Length’, L, ‘Width’, 10e-4*L); % Define length and width
maxEdgeLength = L / 60;
mesh(ant, ‘MaxEdgeLength’, maxEdgeLength);
[currentData, points] = current(ant, f); antenna toolbox, current MATLAB Answers — New Questions
Complex multiplication giving incorrect result
I have a vector A of complex numbers but the product of the numbers should result in real value (there complex conjugate values that make sure the product is real). But when I run prod(A) I get an incorrect result.
A = 1.0e+08 *[-1.1051 + 0.0000i -0.4594 + 1.8182i -0.4594 – 1.8182i -0.2933 + 2.8161i -0.2933 – 2.8161i];
prod(A) = -3.1156e+41 – 9.6714e+24i
The correct value should be -3.1156e+41. why is MATLAB giving incorrect result here?I have a vector A of complex numbers but the product of the numbers should result in real value (there complex conjugate values that make sure the product is real). But when I run prod(A) I get an incorrect result.
A = 1.0e+08 *[-1.1051 + 0.0000i -0.4594 + 1.8182i -0.4594 – 1.8182i -0.2933 + 2.8161i -0.2933 – 2.8161i];
prod(A) = -3.1156e+41 – 9.6714e+24i
The correct value should be -3.1156e+41. why is MATLAB giving incorrect result here? I have a vector A of complex numbers but the product of the numbers should result in real value (there complex conjugate values that make sure the product is real). But when I run prod(A) I get an incorrect result.
A = 1.0e+08 *[-1.1051 + 0.0000i -0.4594 + 1.8182i -0.4594 – 1.8182i -0.2933 + 2.8161i -0.2933 – 2.8161i];
prod(A) = -3.1156e+41 – 9.6714e+24i
The correct value should be -3.1156e+41. why is MATLAB giving incorrect result here? matlab, mathematics MATLAB Answers — New Questions
License borrowing without network access
I’m running Matlab 2014b and I need to install Matlab and borrow one of our floating licenses onto a PC which is not allowed to connect to the internet or intranet.
As far as I can determine, in order to use the license borrowing feature, the PC initially has to be connected to the network. This is not an option for me.
Is there any way to transfer a borrowed license onto a PC without network access – like using a memory stick or similar?I’m running Matlab 2014b and I need to install Matlab and borrow one of our floating licenses onto a PC which is not allowed to connect to the internet or intranet.
As far as I can determine, in order to use the license borrowing feature, the PC initially has to be connected to the network. This is not an option for me.
Is there any way to transfer a borrowed license onto a PC without network access – like using a memory stick or similar? I’m running Matlab 2014b and I need to install Matlab and borrow one of our floating licenses onto a PC which is not allowed to connect to the internet or intranet.
As far as I can determine, in order to use the license borrowing feature, the PC initially has to be connected to the network. This is not an option for me.
Is there any way to transfer a borrowed license onto a PC without network access – like using a memory stick or similar? license borrowing, no network MATLAB Answers — New Questions
How to create text editor in matlab?
I dont know how to create a text editor in matlab.Can anybody help me to create simple text editor.I dont know how to create a text editor in matlab.Can anybody help me to create simple text editor. I dont know how to create a text editor in matlab.Can anybody help me to create simple text editor. text, editor MATLAB Answers — New Questions
How can I control the voxel size using ‘imwrite’?
Hello All,
I have an input tiff file image that has 342 slices, and I would like to extract each slice individually and save as a separate file.
% x = imread("inputTiffFile.tif", 100);
% imwrite(x, "slice_100.tif");
% x = imread("inputTiffFile.tif", 163);
% imwrite(x, "slice_163.tif");
However, I have one problem: The voxel spacing in the input image is [1, 1, 1], but the voxel spacing after using ‘imwrite’ is changed to [0.352778, 0.352778, 1]. I require the voxel spacing to be same as input.
Any inputs on how to avoid this change in voxel size would be very helpful.
Thanks,Hello All,
I have an input tiff file image that has 342 slices, and I would like to extract each slice individually and save as a separate file.
% x = imread("inputTiffFile.tif", 100);
% imwrite(x, "slice_100.tif");
% x = imread("inputTiffFile.tif", 163);
% imwrite(x, "slice_163.tif");
However, I have one problem: The voxel spacing in the input image is [1, 1, 1], but the voxel spacing after using ‘imwrite’ is changed to [0.352778, 0.352778, 1]. I require the voxel spacing to be same as input.
Any inputs on how to avoid this change in voxel size would be very helpful.
Thanks, Hello All,
I have an input tiff file image that has 342 slices, and I would like to extract each slice individually and save as a separate file.
% x = imread("inputTiffFile.tif", 100);
% imwrite(x, "slice_100.tif");
% x = imread("inputTiffFile.tif", 163);
% imwrite(x, "slice_163.tif");
However, I have one problem: The voxel spacing in the input image is [1, 1, 1], but the voxel spacing after using ‘imwrite’ is changed to [0.352778, 0.352778, 1]. I require the voxel spacing to be same as input.
Any inputs on how to avoid this change in voxel size would be very helpful.
Thanks, voxel_spacing, imwrite MATLAB Answers — New Questions
How to disable the display of coverage report once the simulation is stopped
I am in a situation where I need to collect cumulative coverage after multiple simulation restarts. Right now, whenever I hit the stop button, the coverage report is getting generated and it consumes some time, instead am wondering if I can disable the coverage report geneartion and instead save it to a workspace variable and generate the reports at once after all my runs?I am in a situation where I need to collect cumulative coverage after multiple simulation restarts. Right now, whenever I hit the stop button, the coverage report is getting generated and it consumes some time, instead am wondering if I can disable the coverage report geneartion and instead save it to a workspace variable and generate the reports at once after all my runs? I am in a situation where I need to collect cumulative coverage after multiple simulation restarts. Right now, whenever I hit the stop button, the coverage report is getting generated and it consumes some time, instead am wondering if I can disable the coverage report geneartion and instead save it to a workspace variable and generate the reports at once after all my runs? coverage report generation MATLAB Answers — New Questions
How to Calculate dominant frequency and centroid frequency and plot them together
please help me, I would like to calculate dominant and centroid frequency and plot them tohether in one plot. Please CMIIW if i have misundertanding the basic concept. As I undertand, dominant freq is higest freq that appear in our signal. I used FFT and get the max power. And about dominant freq I am not quite sure. What makes me don’t understand is, if I take example from weighted mean as basic of centroid freq, based on example in https://en.wikipedia.org/wiki/Weighted_arithmetic_mean, after calculate weighted mean we have weighted mean of the frequencies present in the signal, meaning that is not a single value. I use spectralCentroid to calculate centroid frequency, but then i confuse, if i have single falue for dominant freq and several value from spectralCentroid, how i should plot them together?
i also attach my file, basically the code will doing looping as my file represent one day data, so my goal is plot dominant and centroid freq in one plot for 1 month. I assume my dominant freq has 30 data point, but not sure about spectralCentroid.
this is my attempt to do it.
sig=load(‘signal2023-335.txt’);
%BAND PASS FILTER long range –> can be considered as UNFILTER condition
% Define the parameters
lowcut = 1/400; % Low cutoff frequency in Hz
high1 = 40; % High cutoff frequency in Hz
high2 = 1.25; % Midrange cutoff frequency in Hz
fs = 100; % Sampling frequency in Hz
% Design the Butterworth bandpass filter (UNFILTER)
[bU, aU] = butter(2,[lowcut high1] / (fs / 2), ‘bandpass’);
sigUnfilt= filtfilt(bU,aU,sig);
% calculate FFT UNFILT
n=length(sigUnfilt);
srate=100; %sampling rate
nyq=srate/2;
fftsig=fft(sigUnfilt-mean(sigUnfilt))/n; %dataX is fft result from filtered signal
hz=linspace(0,nyq,floor(n/2)+1);
pow=2*abs(fftsig(1:length(hz)));
Iv = 1:numel(hz);
%get the maximum freq/dominant freq
[~,idx] = max(pow) ;
domfreq = hz(idx)
% Calculate centroid frequency
centroid = spectralCentroid(sigUnfilt,100)please help me, I would like to calculate dominant and centroid frequency and plot them tohether in one plot. Please CMIIW if i have misundertanding the basic concept. As I undertand, dominant freq is higest freq that appear in our signal. I used FFT and get the max power. And about dominant freq I am not quite sure. What makes me don’t understand is, if I take example from weighted mean as basic of centroid freq, based on example in https://en.wikipedia.org/wiki/Weighted_arithmetic_mean, after calculate weighted mean we have weighted mean of the frequencies present in the signal, meaning that is not a single value. I use spectralCentroid to calculate centroid frequency, but then i confuse, if i have single falue for dominant freq and several value from spectralCentroid, how i should plot them together?
i also attach my file, basically the code will doing looping as my file represent one day data, so my goal is plot dominant and centroid freq in one plot for 1 month. I assume my dominant freq has 30 data point, but not sure about spectralCentroid.
this is my attempt to do it.
sig=load(‘signal2023-335.txt’);
%BAND PASS FILTER long range –> can be considered as UNFILTER condition
% Define the parameters
lowcut = 1/400; % Low cutoff frequency in Hz
high1 = 40; % High cutoff frequency in Hz
high2 = 1.25; % Midrange cutoff frequency in Hz
fs = 100; % Sampling frequency in Hz
% Design the Butterworth bandpass filter (UNFILTER)
[bU, aU] = butter(2,[lowcut high1] / (fs / 2), ‘bandpass’);
sigUnfilt= filtfilt(bU,aU,sig);
% calculate FFT UNFILT
n=length(sigUnfilt);
srate=100; %sampling rate
nyq=srate/2;
fftsig=fft(sigUnfilt-mean(sigUnfilt))/n; %dataX is fft result from filtered signal
hz=linspace(0,nyq,floor(n/2)+1);
pow=2*abs(fftsig(1:length(hz)));
Iv = 1:numel(hz);
%get the maximum freq/dominant freq
[~,idx] = max(pow) ;
domfreq = hz(idx)
% Calculate centroid frequency
centroid = spectralCentroid(sigUnfilt,100) please help me, I would like to calculate dominant and centroid frequency and plot them tohether in one plot. Please CMIIW if i have misundertanding the basic concept. As I undertand, dominant freq is higest freq that appear in our signal. I used FFT and get the max power. And about dominant freq I am not quite sure. What makes me don’t understand is, if I take example from weighted mean as basic of centroid freq, based on example in https://en.wikipedia.org/wiki/Weighted_arithmetic_mean, after calculate weighted mean we have weighted mean of the frequencies present in the signal, meaning that is not a single value. I use spectralCentroid to calculate centroid frequency, but then i confuse, if i have single falue for dominant freq and several value from spectralCentroid, how i should plot them together?
i also attach my file, basically the code will doing looping as my file represent one day data, so my goal is plot dominant and centroid freq in one plot for 1 month. I assume my dominant freq has 30 data point, but not sure about spectralCentroid.
this is my attempt to do it.
sig=load(‘signal2023-335.txt’);
%BAND PASS FILTER long range –> can be considered as UNFILTER condition
% Define the parameters
lowcut = 1/400; % Low cutoff frequency in Hz
high1 = 40; % High cutoff frequency in Hz
high2 = 1.25; % Midrange cutoff frequency in Hz
fs = 100; % Sampling frequency in Hz
% Design the Butterworth bandpass filter (UNFILTER)
[bU, aU] = butter(2,[lowcut high1] / (fs / 2), ‘bandpass’);
sigUnfilt= filtfilt(bU,aU,sig);
% calculate FFT UNFILT
n=length(sigUnfilt);
srate=100; %sampling rate
nyq=srate/2;
fftsig=fft(sigUnfilt-mean(sigUnfilt))/n; %dataX is fft result from filtered signal
hz=linspace(0,nyq,floor(n/2)+1);
pow=2*abs(fftsig(1:length(hz)));
Iv = 1:numel(hz);
%get the maximum freq/dominant freq
[~,idx] = max(pow) ;
domfreq = hz(idx)
% Calculate centroid frequency
centroid = spectralCentroid(sigUnfilt,100) centroid frequency, fft, centroid, weighted mean MATLAB Answers — New Questions
Matlab R2019b no window manager on Ubuntu 18.04
Hi,
Recently when I start matlab the application has no window manager i.e. no top bar, minimize/maximize buttons etc. Even the keyboard shortcuts for these actions have no effect. This behaviour started recently and I am not sure why or how to find the root cause. Does anyone have any hints?
Thanks in advance.Hi,
Recently when I start matlab the application has no window manager i.e. no top bar, minimize/maximize buttons etc. Even the keyboard shortcuts for these actions have no effect. This behaviour started recently and I am not sure why or how to find the root cause. Does anyone have any hints?
Thanks in advance. Hi,
Recently when I start matlab the application has no window manager i.e. no top bar, minimize/maximize buttons etc. Even the keyboard shortcuts for these actions have no effect. This behaviour started recently and I am not sure why or how to find the root cause. Does anyone have any hints?
Thanks in advance. ubuntu MATLAB Answers — New Questions
Find imapedance of a circuit with mesured current and voltage and frequency sweep(up to 1MHz). C and L are unknow.
I have a mesured voltage and current. I want to find the impedance magnitude, real and imaginary part then plot yquist and cole-cole plot, but i don’t know to proceed, can someone help please.I have a mesured voltage and current. I want to find the impedance magnitude, real and imaginary part then plot yquist and cole-cole plot, but i don’t know to proceed, can someone help please. I have a mesured voltage and current. I want to find the impedance magnitude, real and imaginary part then plot yquist and cole-cole plot, but i don’t know to proceed, can someone help please. impedance, varying frequency, frequency sweep, nyquist, cole cole plot MATLAB Answers — New Questions
Vertically Concatenating Timetables of Different Sizes
As the title states, I wish to do just that. More specifically, I need to combine n timetables, each with one row, but varying column counts (Dimension counts). There is a nonzero intersection between each timetable, and so there are data being shared between each. However, some may also have data that other’s do not.
The goal here is to vertically concatenate each timetable so that all the data within the intersection are aligned by column/dimension name type. If there are data that are missing and so one timetable is smaller than the other, then that dimension/data type will be populated as a ‘NaN’ within the smaller timetable. In the example I give below, I say there are three timetables of lengths 1×40, 1×36 and 1×30. I wish to get a resulting timetable that is then 3×40.
Method 1:
Obviously doesn’t work as the # of columns are different.
Method 2:
I tried using a solution on another post that does exactly what I want, but with tables instead of timetables. This did not give the correct result as the output is a 3×215, which I don’t understand why. It also combines the dimension labels with “All” which doesn’t make sense to me as I specify “MergeKeys” as “True” which should leave the dimension labels alone according to the documentation. It comes close though in that it does concatenate the datetimes correctly and populates empty data/units with ‘NaN’s. I tried specifying the “Key” variables to align to, but because some timetables do not contain these variables and the Matlab function outerjoin wasn’t built to create missing variable columns that auto populate with NaNs when it encounters this, this does not work.
Method 3:
I tried using the synchronize function as this is specifically geared towards timetables. I get the exact same resulting timetable as Method 2. The synchronize documentation and "Combine Timetables and Synchronize Their Data" documentation give examples that do the exact same thing (Just that I have more columns and different dimension names) as my example from what I can see, so I am even more confused by why this does not produce the same result that I would like.
So I think I am just not employing Methods 2,3 correctly or I may have to create another for-loop prior to concatenation that creates the new variables in the smaller timetables and populates them with NaNs using indexing of the largest timetable.
%Create 3 timetables of different sizes and random dimension names with nonzero intersections
varTypes = {‘string’};
doub = ‘double’;
str = ‘string’;
szList = [40,36,30];
ind = {‘A’,’B’,’C’};
TimeDim = [datetime(‘2023-01-01 20:14:58’),datetime(‘2023-02-21 22:13:04’),datetime(‘2023-03-11 10:12:58’)];
for i = 1:length(szList)
for j = 1:szList(i)
varTypes{end+1} = doub;
varTypes{end+1} = str;
end
ArrayList.ind{i} = varTypes;
varTypes = {‘string’};
end
clear i j
for i = 1:length(szList)
ttSaved.ind{i} = timetable(‘Size’,[1 2*szList(i)+1],’VariableTypes’,ArrayList.ind{1,i},’RowTimes’,TimeDim(i));
ttSaved.ind{i} = renamevars(ttSaved.ind{i},’Var1′,’Exp_ID’);
ttSaved.ind{i}.Exp_ID = i;
end
clear i
%Label each dimenion and populate tables with data
for i = 1:length(ttSaved.ind)
choice = randperm(szList(i));
for j = 1:szList(i)
ttSaved.ind{i} = renamevars(ttSaved.ind{i},sprintf(‘Var%d’,2*j),sprintf(‘Data_%d’,choice(j)));
ttSaved.ind{i} = renamevars(ttSaved.ind{i},sprintf(‘Var%d’,2*j+1),sprintf(‘Units_%d’,choice(j)));
end
Names = ttSaved.ind{i}.Properties.VariableNames;
for k = 1:szList(i)
ttSaved.ind{i}.(Names{2*k}) = rand*100; %Add data
ttSaved.ind{i}.(Names{2*k+1}) = char(choice(k)); %Add Units
end
end
clear i j k
%Method 1
ttAll = [];
for i = 1:length(ttSaved.ind)
ttAll = [ttAll ; ttSaved.ind{i}];
end
clear i
%Method 2
ttAll = ttSaved.ind{1};
AllMeas = ttSaved.ind{1}.Properties.VariableNames;
for i = 2:length(ttSaved.ind)
ttAll = outerjoin(ttAll,ttSaved.ind{i},’Keys’,AllMeas,’MergeKeys’, true);
end
clear i
%Method 3
ttAll2 = ttSaved.ind{1};
for i = 2:length(ttSaved.ind)
ttAll2 = synchronize(ttAll2,ttSaved.ind{i});
end
clear i
Note: This post is somewhat of a continuation of a previous post, but since I marked the last as answered and this one is different enough and contains the same data structures to my actual data, I needed create a new question.As the title states, I wish to do just that. More specifically, I need to combine n timetables, each with one row, but varying column counts (Dimension counts). There is a nonzero intersection between each timetable, and so there are data being shared between each. However, some may also have data that other’s do not.
The goal here is to vertically concatenate each timetable so that all the data within the intersection are aligned by column/dimension name type. If there are data that are missing and so one timetable is smaller than the other, then that dimension/data type will be populated as a ‘NaN’ within the smaller timetable. In the example I give below, I say there are three timetables of lengths 1×40, 1×36 and 1×30. I wish to get a resulting timetable that is then 3×40.
Method 1:
Obviously doesn’t work as the # of columns are different.
Method 2:
I tried using a solution on another post that does exactly what I want, but with tables instead of timetables. This did not give the correct result as the output is a 3×215, which I don’t understand why. It also combines the dimension labels with “All” which doesn’t make sense to me as I specify “MergeKeys” as “True” which should leave the dimension labels alone according to the documentation. It comes close though in that it does concatenate the datetimes correctly and populates empty data/units with ‘NaN’s. I tried specifying the “Key” variables to align to, but because some timetables do not contain these variables and the Matlab function outerjoin wasn’t built to create missing variable columns that auto populate with NaNs when it encounters this, this does not work.
Method 3:
I tried using the synchronize function as this is specifically geared towards timetables. I get the exact same resulting timetable as Method 2. The synchronize documentation and "Combine Timetables and Synchronize Their Data" documentation give examples that do the exact same thing (Just that I have more columns and different dimension names) as my example from what I can see, so I am even more confused by why this does not produce the same result that I would like.
So I think I am just not employing Methods 2,3 correctly or I may have to create another for-loop prior to concatenation that creates the new variables in the smaller timetables and populates them with NaNs using indexing of the largest timetable.
%Create 3 timetables of different sizes and random dimension names with nonzero intersections
varTypes = {‘string’};
doub = ‘double’;
str = ‘string’;
szList = [40,36,30];
ind = {‘A’,’B’,’C’};
TimeDim = [datetime(‘2023-01-01 20:14:58’),datetime(‘2023-02-21 22:13:04’),datetime(‘2023-03-11 10:12:58’)];
for i = 1:length(szList)
for j = 1:szList(i)
varTypes{end+1} = doub;
varTypes{end+1} = str;
end
ArrayList.ind{i} = varTypes;
varTypes = {‘string’};
end
clear i j
for i = 1:length(szList)
ttSaved.ind{i} = timetable(‘Size’,[1 2*szList(i)+1],’VariableTypes’,ArrayList.ind{1,i},’RowTimes’,TimeDim(i));
ttSaved.ind{i} = renamevars(ttSaved.ind{i},’Var1′,’Exp_ID’);
ttSaved.ind{i}.Exp_ID = i;
end
clear i
%Label each dimenion and populate tables with data
for i = 1:length(ttSaved.ind)
choice = randperm(szList(i));
for j = 1:szList(i)
ttSaved.ind{i} = renamevars(ttSaved.ind{i},sprintf(‘Var%d’,2*j),sprintf(‘Data_%d’,choice(j)));
ttSaved.ind{i} = renamevars(ttSaved.ind{i},sprintf(‘Var%d’,2*j+1),sprintf(‘Units_%d’,choice(j)));
end
Names = ttSaved.ind{i}.Properties.VariableNames;
for k = 1:szList(i)
ttSaved.ind{i}.(Names{2*k}) = rand*100; %Add data
ttSaved.ind{i}.(Names{2*k+1}) = char(choice(k)); %Add Units
end
end
clear i j k
%Method 1
ttAll = [];
for i = 1:length(ttSaved.ind)
ttAll = [ttAll ; ttSaved.ind{i}];
end
clear i
%Method 2
ttAll = ttSaved.ind{1};
AllMeas = ttSaved.ind{1}.Properties.VariableNames;
for i = 2:length(ttSaved.ind)
ttAll = outerjoin(ttAll,ttSaved.ind{i},’Keys’,AllMeas,’MergeKeys’, true);
end
clear i
%Method 3
ttAll2 = ttSaved.ind{1};
for i = 2:length(ttSaved.ind)
ttAll2 = synchronize(ttAll2,ttSaved.ind{i});
end
clear i
Note: This post is somewhat of a continuation of a previous post, but since I marked the last as answered and this one is different enough and contains the same data structures to my actual data, I needed create a new question. As the title states, I wish to do just that. More specifically, I need to combine n timetables, each with one row, but varying column counts (Dimension counts). There is a nonzero intersection between each timetable, and so there are data being shared between each. However, some may also have data that other’s do not.
The goal here is to vertically concatenate each timetable so that all the data within the intersection are aligned by column/dimension name type. If there are data that are missing and so one timetable is smaller than the other, then that dimension/data type will be populated as a ‘NaN’ within the smaller timetable. In the example I give below, I say there are three timetables of lengths 1×40, 1×36 and 1×30. I wish to get a resulting timetable that is then 3×40.
Method 1:
Obviously doesn’t work as the # of columns are different.
Method 2:
I tried using a solution on another post that does exactly what I want, but with tables instead of timetables. This did not give the correct result as the output is a 3×215, which I don’t understand why. It also combines the dimension labels with “All” which doesn’t make sense to me as I specify “MergeKeys” as “True” which should leave the dimension labels alone according to the documentation. It comes close though in that it does concatenate the datetimes correctly and populates empty data/units with ‘NaN’s. I tried specifying the “Key” variables to align to, but because some timetables do not contain these variables and the Matlab function outerjoin wasn’t built to create missing variable columns that auto populate with NaNs when it encounters this, this does not work.
Method 3:
I tried using the synchronize function as this is specifically geared towards timetables. I get the exact same resulting timetable as Method 2. The synchronize documentation and "Combine Timetables and Synchronize Their Data" documentation give examples that do the exact same thing (Just that I have more columns and different dimension names) as my example from what I can see, so I am even more confused by why this does not produce the same result that I would like.
So I think I am just not employing Methods 2,3 correctly or I may have to create another for-loop prior to concatenation that creates the new variables in the smaller timetables and populates them with NaNs using indexing of the largest timetable.
%Create 3 timetables of different sizes and random dimension names with nonzero intersections
varTypes = {‘string’};
doub = ‘double’;
str = ‘string’;
szList = [40,36,30];
ind = {‘A’,’B’,’C’};
TimeDim = [datetime(‘2023-01-01 20:14:58’),datetime(‘2023-02-21 22:13:04’),datetime(‘2023-03-11 10:12:58’)];
for i = 1:length(szList)
for j = 1:szList(i)
varTypes{end+1} = doub;
varTypes{end+1} = str;
end
ArrayList.ind{i} = varTypes;
varTypes = {‘string’};
end
clear i j
for i = 1:length(szList)
ttSaved.ind{i} = timetable(‘Size’,[1 2*szList(i)+1],’VariableTypes’,ArrayList.ind{1,i},’RowTimes’,TimeDim(i));
ttSaved.ind{i} = renamevars(ttSaved.ind{i},’Var1′,’Exp_ID’);
ttSaved.ind{i}.Exp_ID = i;
end
clear i
%Label each dimenion and populate tables with data
for i = 1:length(ttSaved.ind)
choice = randperm(szList(i));
for j = 1:szList(i)
ttSaved.ind{i} = renamevars(ttSaved.ind{i},sprintf(‘Var%d’,2*j),sprintf(‘Data_%d’,choice(j)));
ttSaved.ind{i} = renamevars(ttSaved.ind{i},sprintf(‘Var%d’,2*j+1),sprintf(‘Units_%d’,choice(j)));
end
Names = ttSaved.ind{i}.Properties.VariableNames;
for k = 1:szList(i)
ttSaved.ind{i}.(Names{2*k}) = rand*100; %Add data
ttSaved.ind{i}.(Names{2*k+1}) = char(choice(k)); %Add Units
end
end
clear i j k
%Method 1
ttAll = [];
for i = 1:length(ttSaved.ind)
ttAll = [ttAll ; ttSaved.ind{i}];
end
clear i
%Method 2
ttAll = ttSaved.ind{1};
AllMeas = ttSaved.ind{1}.Properties.VariableNames;
for i = 2:length(ttSaved.ind)
ttAll = outerjoin(ttAll,ttSaved.ind{i},’Keys’,AllMeas,’MergeKeys’, true);
end
clear i
%Method 3
ttAll2 = ttSaved.ind{1};
for i = 2:length(ttSaved.ind)
ttAll2 = synchronize(ttAll2,ttSaved.ind{i});
end
clear i
Note: This post is somewhat of a continuation of a previous post, but since I marked the last as answered and this one is different enough and contains the same data structures to my actual data, I needed create a new question. timetables, concatenating timetables, concatenation, synchronize MATLAB Answers — New Questions
Geotagging my coordinates with images
Hi,there . The code that i want to write is :(i have a file of images and each images has a gps coordination in my csv excel file , well i need a code that gets a coordinates from my excel and tags it to it’s own picture… and at the end when i get the properties of my pictures i can see the coordinates in details) … i wrote to many codes but I wasn’t successful …plz help me to solve it ..thank you . And i took an example of my code .
Picfile=(“address”);coordsfile=(“address.csv”);
for i = 1:height(coords)
filename = coords.Filename{i};
lat = coords.Latitude(i);
lon = coords.Longitude(i);
command = sprintf( lat, lon, filename);
system([‘exiftool ‘ command]);
endHi,there . The code that i want to write is :(i have a file of images and each images has a gps coordination in my csv excel file , well i need a code that gets a coordinates from my excel and tags it to it’s own picture… and at the end when i get the properties of my pictures i can see the coordinates in details) … i wrote to many codes but I wasn’t successful …plz help me to solve it ..thank you . And i took an example of my code .
Picfile=(“address”);coordsfile=(“address.csv”);
for i = 1:height(coords)
filename = coords.Filename{i};
lat = coords.Latitude(i);
lon = coords.Longitude(i);
command = sprintf( lat, lon, filename);
system([‘exiftool ‘ command]);
end Hi,there . The code that i want to write is :(i have a file of images and each images has a gps coordination in my csv excel file , well i need a code that gets a coordinates from my excel and tags it to it’s own picture… and at the end when i get the properties of my pictures i can see the coordinates in details) … i wrote to many codes but I wasn’t successful …plz help me to solve it ..thank you . And i took an example of my code .
Picfile=(“address”);coordsfile=(“address.csv”);
for i = 1:height(coords)
filename = coords.Filename{i};
lat = coords.Latitude(i);
lon = coords.Longitude(i);
command = sprintf( lat, lon, filename);
system([‘exiftool ‘ command]);
end tagging MATLAB Answers — New Questions
‘parpool(2)’ fails
Hi, I am testing some MATLAB code via GitHub Action. Strange bug occurs when I was testing `parpool(2)` with MATLAB R2021b and R2022a on Mac and Ubuntu as follows.
Error using parpool
Undefined function ‘pCurrentTaskIsPartOfAPool’ for input arguments of type
‘double’.
Error in solveAllProblems (line 68)
parpool(numJobs);
The code is fine with the latest verion of MATLAB.
Any comment helps.Hi, I am testing some MATLAB code via GitHub Action. Strange bug occurs when I was testing `parpool(2)` with MATLAB R2021b and R2022a on Mac and Ubuntu as follows.
Error using parpool
Undefined function ‘pCurrentTaskIsPartOfAPool’ for input arguments of type
‘double’.
Error in solveAllProblems (line 68)
parpool(numJobs);
The code is fine with the latest verion of MATLAB.
Any comment helps. Hi, I am testing some MATLAB code via GitHub Action. Strange bug occurs when I was testing `parpool(2)` with MATLAB R2021b and R2022a on Mac and Ubuntu as follows.
Error using parpool
Undefined function ‘pCurrentTaskIsPartOfAPool’ for input arguments of type
‘double’.
Error in solveAllProblems (line 68)
parpool(numJobs);
The code is fine with the latest verion of MATLAB.
Any comment helps. parfor, parallel computing, parallel computing toolbox MATLAB Answers — New Questions
How can you add GPS location data to a Image
I am trying to combine GPS data and video. I have a GPS device which gives me gps/nmea format gps data. I am reading each frame from the video and storing it as a image and want to add GPSInfo (metadata) to it. If I use the IMWRITE function, it doesn’t let me add the GPSInfo data since its not a tag which can be edited or changed.
How can I then geotag images using MATLAB?I am trying to combine GPS data and video. I have a GPS device which gives me gps/nmea format gps data. I am reading each frame from the video and storing it as a image and want to add GPSInfo (metadata) to it. If I use the IMWRITE function, it doesn’t let me add the GPSInfo data since its not a tag which can be edited or changed.
How can I then geotag images using MATLAB? I am trying to combine GPS data and video. I have a GPS device which gives me gps/nmea format gps data. I am reading each frame from the video and storing it as a image and want to add GPSInfo (metadata) to it. If I use the IMWRITE function, it doesn’t let me add the GPSInfo data since its not a tag which can be edited or changed.
How can I then geotag images using MATLAB? geotagging images, gps, video processing, gps tagging MATLAB Answers — New Questions
Como evaluar un curso hecho en la plataforma de Matlab?
Estoy organizando un curso de introduccion a Matlab, quero saber el como evaluar el avance y desarrollo de las cursos online, que se enseña en la plataforma.Estoy organizando un curso de introduccion a Matlab, quero saber el como evaluar el avance y desarrollo de las cursos online, que se enseña en la plataforma. Estoy organizando un curso de introduccion a Matlab, quero saber el como evaluar el avance y desarrollo de las cursos online, que se enseña en la plataforma. cursos, online, evaluacion, matlab MATLAB Answers — New Questions
How can I use Createpde to solve a fourth degree partial differential equation?
Hello,
How can I use Createpde to solve the a fourth degree partial differential equation?
∇4(u)=q/D?Hello,
How can I use Createpde to solve the a fourth degree partial differential equation?
∇4(u)=q/D? Hello,
How can I use Createpde to solve the a fourth degree partial differential equation?
∇4(u)=q/D? createpde MATLAB Answers — New Questions
Generation of C++ Code from DAGNetwork fails
Dear cummunity,
I try to generate C/C++ code from an DAGNetwork, which is generated imported from an ONNX model. When I try to run this model in MATLAB itself, no errrors occour. The model is saved as *.mat file. Loading and running the model again is working well.
If I want to generate C/C++ code from the model via the following code (in two separate files gencode.m and myNet_predict.m), I get the error message: ??? Layer hyper-parameters for custom layer ‘PadLayer1183’ must be numeric scalar, scalar logical, character or string array, or a matrix of type double or single.
% codegen.m
cfg = coder.config(‘mex’);
cfg.TargetLang = ‘C++’;
cfg.DeepLearningConfig = coder.DeepLearningConfig(‘mkldnn’);
args = {zeros(1024,1024,3,’single’)};
codegen -config cfg -args args myNet_predict -report
% myNet_predict.m
function out = myNet_predict(img)
persistent mynet;
if isempty(mynet)
mynet = coder.loadDeepLearningNetwork(‘DeepLabV3plus.mat’);
end
pred = predict(mynet, img);
end
Unfortunately the *.mat files of the neural network and PadLayer1183 are to big for uploading here, I uploaded them under https://cloudstore.zih.tu-dresden.de/index.php/s/ajSCte9G9HN2pqP for save downloading. These are all files which are neccessary to reproduce the discribed behaviour.
I tried to debug the code so far, but I do not got an idea why this error occours. As I followed the compilation process, the error appears only when the prediction is called.
The input is every time an image with the dimension 1024x1024x3. I know its very big, but thats a requirement of the neural network. I guess that the problem is the attribute ONNXParams from the type ONNXParameters. Because it would be a very huge workaround to replace this variable with single parameters, I do not think that MATLAB would handle code generations in this way.
Hopefully anyone can help me to figure out whats wrong in the model code or my code.
Thanks in advance.
Best regardsDear cummunity,
I try to generate C/C++ code from an DAGNetwork, which is generated imported from an ONNX model. When I try to run this model in MATLAB itself, no errrors occour. The model is saved as *.mat file. Loading and running the model again is working well.
If I want to generate C/C++ code from the model via the following code (in two separate files gencode.m and myNet_predict.m), I get the error message: ??? Layer hyper-parameters for custom layer ‘PadLayer1183’ must be numeric scalar, scalar logical, character or string array, or a matrix of type double or single.
% codegen.m
cfg = coder.config(‘mex’);
cfg.TargetLang = ‘C++’;
cfg.DeepLearningConfig = coder.DeepLearningConfig(‘mkldnn’);
args = {zeros(1024,1024,3,’single’)};
codegen -config cfg -args args myNet_predict -report
% myNet_predict.m
function out = myNet_predict(img)
persistent mynet;
if isempty(mynet)
mynet = coder.loadDeepLearningNetwork(‘DeepLabV3plus.mat’);
end
pred = predict(mynet, img);
end
Unfortunately the *.mat files of the neural network and PadLayer1183 are to big for uploading here, I uploaded them under https://cloudstore.zih.tu-dresden.de/index.php/s/ajSCte9G9HN2pqP for save downloading. These are all files which are neccessary to reproduce the discribed behaviour.
I tried to debug the code so far, but I do not got an idea why this error occours. As I followed the compilation process, the error appears only when the prediction is called.
The input is every time an image with the dimension 1024x1024x3. I know its very big, but thats a requirement of the neural network. I guess that the problem is the attribute ONNXParams from the type ONNXParameters. Because it would be a very huge workaround to replace this variable with single parameters, I do not think that MATLAB would handle code generations in this way.
Hopefully anyone can help me to figure out whats wrong in the model code or my code.
Thanks in advance.
Best regards Dear cummunity,
I try to generate C/C++ code from an DAGNetwork, which is generated imported from an ONNX model. When I try to run this model in MATLAB itself, no errrors occour. The model is saved as *.mat file. Loading and running the model again is working well.
If I want to generate C/C++ code from the model via the following code (in two separate files gencode.m and myNet_predict.m), I get the error message: ??? Layer hyper-parameters for custom layer ‘PadLayer1183’ must be numeric scalar, scalar logical, character or string array, or a matrix of type double or single.
% codegen.m
cfg = coder.config(‘mex’);
cfg.TargetLang = ‘C++’;
cfg.DeepLearningConfig = coder.DeepLearningConfig(‘mkldnn’);
args = {zeros(1024,1024,3,’single’)};
codegen -config cfg -args args myNet_predict -report
% myNet_predict.m
function out = myNet_predict(img)
persistent mynet;
if isempty(mynet)
mynet = coder.loadDeepLearningNetwork(‘DeepLabV3plus.mat’);
end
pred = predict(mynet, img);
end
Unfortunately the *.mat files of the neural network and PadLayer1183 are to big for uploading here, I uploaded them under https://cloudstore.zih.tu-dresden.de/index.php/s/ajSCte9G9HN2pqP for save downloading. These are all files which are neccessary to reproduce the discribed behaviour.
I tried to debug the code so far, but I do not got an idea why this error occours. As I followed the compilation process, the error appears only when the prediction is called.
The input is every time an image with the dimension 1024x1024x3. I know its very big, but thats a requirement of the neural network. I guess that the problem is the attribute ONNXParams from the type ONNXParameters. Because it would be a very huge workaround to replace this variable with single parameters, I do not think that MATLAB would handle code generations in this way.
Hopefully anyone can help me to figure out whats wrong in the model code or my code.
Thanks in advance.
Best regards deep learning, matlab coder, c++, neural network, onnx, mex MATLAB Answers — New Questions
MATLAB-YALMIP optimal trendy program cannot converge
I use MATLAB-YALMIP to write the optimal trend program based on the IEEEE14 system, but I can’t converge. Please help to see if the program is wrong?
code:
% Optimal Power Flow Example
% Based on the IEEE 14-bus standard case (i.e., case14 in Matpower)
% Implemented in MATLAB with YALMIP
clear; clc;
% Load power system data
mpc = loadcase(‘case14’); % You can also load other data files, such as case9, case30, etc.
% Define variables and parameters
nb = size(mpc.bus, 1); % Number of buses (nodes)
nl = size(mpc.branch, 1); % Number of branches (lines)
ng = size(mpc.gen, 1); % Number of generators
nr = nb – ng; % Number of load buses
% Extract node data
bus_id = mpc.bus(:, 1); % Bus IDs
bus_type = mpc.bus(:, 2); % Bus types (1-PQ, 2-PV, 3-Slack)
Pd = mpc.bus(:, 3); % Active power demand (MW)
Qd = mpc.bus(:, 4); % Reactive power demand (MVAr)
Vmin = mpc.bus(:, 13); % Minimum bus voltage (p.u.)
Vmax = mpc.bus(:, 12); % Maximum bus voltage (p.u.)
% Extract generator data
gen_id = mpc.gen(:, 1); % Bus IDs where generators are connected
Pgmin = mpc.gen(:, 10); % Minimum generator active power output (MW)
Pgmax = mpc.gen(:, 9); % Maximum generator active power output (MW)
Qgmin = mpc.gen(:, 5); % Minimum generator reactive power output (MVAr)
Qgmax = mpc.gen(:, 4); % Maximum generator reactive power output (MVAr)
a2 = mpc.gencost(:, 5); % Generator cost curve coefficient for quadratic term
a1 = mpc.gencost(:, 6); % Generator cost curve coefficient for linear term
a0 = mpc.gencost(:, 7); % Generator cost curve constant term
% Extract branch data
fbus = mpc.branch(:, 1); % "From" bus (starting node) of each branch
tbus = mpc.branch(:, 2); % "To" bus (ending node) of each branch
Plmax = ones(nl, 1) * 4000; % Maximum branch active power flow limit (MW)
% Plmax = mpc.branch(:, 6) .* mpc.branch(:, 3) * 1e-3; % Maximum branch active power flow limit (MW)
% Calculate the bus admittance matrix
[Ybus, ~, ~] = makeYbus(mpc); % Use a Matpower function to calculate the bus admittance matrix
Gbus = real(Ybus); % Real part of bus admittance matrix (conductance)
Bbus = imag(Ybus); % Imaginary part of bus admittance matrix (susceptance)
% Define YALMIP variables
Pg = sdpvar(ng, 1, ‘full’); % Generator active power output variables
Qg = sdpvar(ng, 1, ‘full’); % Generator reactive power output variables
V = sdpvar(nb, 1, ‘full’); % Bus voltage magnitude variables
theta = sdpvar(nb, 1, ‘full’); % Bus voltage angle variables
Pl = sdpvar(nl, 1, ‘full’); % Branch active power flow variables
% Define the objective function
objective = sum(a2 .* Pg.^2 + a1 .* Pg + a0); % Minimize the total operating cost
% Define constraints
constraints = [];
% Node power balance constraints
for i = 1:nb
% Active power balance equation for node i
if ismember(i, gen_id)
record = find(gen_id == i);
constraints = [constraints, Pg(record) – Pd(i) – V(i) * sum(V * (Gbus(i, 🙂 * cos(theta(i) – theta) + Bbus(i, 🙂 * sin(theta(i) – theta))) == 0];
constraints = [constraints, Qg(record) – Qd(i) + V(i) * sum(V * (Gbus(i, 🙂 * sin(theta(i) – theta) – Bbus(i, 🙂 * cos(theta(i) – theta))) == 0];
else
constraints = [constraints, -Pd(i) – V(i) * sum(V * (Gbus(i, 🙂 * cos(theta(i) – theta) + Bbus(i, 🙂 * sin(theta(i) – theta))) == 0];
constraints = [constraints, -Qd(i) + V(i) * sum(V * (Gbus(i, 🙂 * sin(theta(i) – theta) – Bbus(i, 🙂 * cos(theta(i) – theta))) == 0];
end
end
% Generator output limit constraints
for i = 1:ng
% Minimum active power output constraint for generator i
constraints = [constraints, Pgmin(i) <= Pg(i)];
% Maximum active power output constraint for generator i
constraints = [constraints, Pg(i) <= Pgmax(i)];
% Minimum reactive power output constraint for generator i
constraints = [constraints, Qgmin(i) <= Qg(i)];
% Maximum reactive power output constraint for generator i
constraints = [constraints, Qg(i) <= Qgmax(i)];
end
% Bus voltage limit constraints
for i = 1:nb
% Minimum bus voltage magnitude constraint for bus i
constraints = [constraints, Vmin(i) <= V(i)];
% Maximum bus voltage magnitude constraint for bus i
constraints = [constraints, V(i) <= Vmax(i)];
end
% Branch power flow limit constraints
for i = 1:nl
% Calculate active power flow on branch i (assuming the "from" bus is the positive direction)
Pl(i) = V(fbus(i))^2 * Gbus(fbus(i), tbus(i)) – V(fbus(i)) * V(tbus(i)) * (Gbus(fbus(i), tbus(i)) * cos(theta(fbus(i) – theta(tbus(i))) + Bbus(fbus(i), tbus(i)) * sin(theta(fbus(i) – theta(tbus(i)))));
% Absolute value constraint for active power flow on branch i
constraints = [constraints, abs(Pl(i)) <= Plmax(i)];
end
% Solve the optimal power flow problem
result = solvesdp(constraints, objective); % Use YALMIP to solve the optimal power flow problem
% Output and analyze the results
if result.problem == 0 % If the solution is successful
disp(‘Optimal Power Flow Solved Successfully!’); % Display success message
disp(‘Total System Operating Cost:’); % Display total system operating cost
value(objective) % Display the objective function value
disp(‘Generator Active Power Output:’); % Display generator active power output
value(Pg) % Display the generator active power output variable values
disp(‘Generator Reactive Power Output:’); % Display generator reactive power output
value(Qg) % Display the generator reactive power output variable values
disp(‘Bus Voltage Magnitude:’); % Display bus voltage magnitude
value(V) % Display the bus voltage magnitude variable values
disp(‘Bus Voltage Angle (in degrees):’); % Display bus voltage angle (in degrees)
rad2deg(value(theta)) % Display bus voltage angle variable values and convert to degrees
disp(‘Branch Active Power Flow:’); % Display branch active power flow
value(Pl)
endI use MATLAB-YALMIP to write the optimal trend program based on the IEEEE14 system, but I can’t converge. Please help to see if the program is wrong?
code:
% Optimal Power Flow Example
% Based on the IEEE 14-bus standard case (i.e., case14 in Matpower)
% Implemented in MATLAB with YALMIP
clear; clc;
% Load power system data
mpc = loadcase(‘case14’); % You can also load other data files, such as case9, case30, etc.
% Define variables and parameters
nb = size(mpc.bus, 1); % Number of buses (nodes)
nl = size(mpc.branch, 1); % Number of branches (lines)
ng = size(mpc.gen, 1); % Number of generators
nr = nb – ng; % Number of load buses
% Extract node data
bus_id = mpc.bus(:, 1); % Bus IDs
bus_type = mpc.bus(:, 2); % Bus types (1-PQ, 2-PV, 3-Slack)
Pd = mpc.bus(:, 3); % Active power demand (MW)
Qd = mpc.bus(:, 4); % Reactive power demand (MVAr)
Vmin = mpc.bus(:, 13); % Minimum bus voltage (p.u.)
Vmax = mpc.bus(:, 12); % Maximum bus voltage (p.u.)
% Extract generator data
gen_id = mpc.gen(:, 1); % Bus IDs where generators are connected
Pgmin = mpc.gen(:, 10); % Minimum generator active power output (MW)
Pgmax = mpc.gen(:, 9); % Maximum generator active power output (MW)
Qgmin = mpc.gen(:, 5); % Minimum generator reactive power output (MVAr)
Qgmax = mpc.gen(:, 4); % Maximum generator reactive power output (MVAr)
a2 = mpc.gencost(:, 5); % Generator cost curve coefficient for quadratic term
a1 = mpc.gencost(:, 6); % Generator cost curve coefficient for linear term
a0 = mpc.gencost(:, 7); % Generator cost curve constant term
% Extract branch data
fbus = mpc.branch(:, 1); % "From" bus (starting node) of each branch
tbus = mpc.branch(:, 2); % "To" bus (ending node) of each branch
Plmax = ones(nl, 1) * 4000; % Maximum branch active power flow limit (MW)
% Plmax = mpc.branch(:, 6) .* mpc.branch(:, 3) * 1e-3; % Maximum branch active power flow limit (MW)
% Calculate the bus admittance matrix
[Ybus, ~, ~] = makeYbus(mpc); % Use a Matpower function to calculate the bus admittance matrix
Gbus = real(Ybus); % Real part of bus admittance matrix (conductance)
Bbus = imag(Ybus); % Imaginary part of bus admittance matrix (susceptance)
% Define YALMIP variables
Pg = sdpvar(ng, 1, ‘full’); % Generator active power output variables
Qg = sdpvar(ng, 1, ‘full’); % Generator reactive power output variables
V = sdpvar(nb, 1, ‘full’); % Bus voltage magnitude variables
theta = sdpvar(nb, 1, ‘full’); % Bus voltage angle variables
Pl = sdpvar(nl, 1, ‘full’); % Branch active power flow variables
% Define the objective function
objective = sum(a2 .* Pg.^2 + a1 .* Pg + a0); % Minimize the total operating cost
% Define constraints
constraints = [];
% Node power balance constraints
for i = 1:nb
% Active power balance equation for node i
if ismember(i, gen_id)
record = find(gen_id == i);
constraints = [constraints, Pg(record) – Pd(i) – V(i) * sum(V * (Gbus(i, 🙂 * cos(theta(i) – theta) + Bbus(i, 🙂 * sin(theta(i) – theta))) == 0];
constraints = [constraints, Qg(record) – Qd(i) + V(i) * sum(V * (Gbus(i, 🙂 * sin(theta(i) – theta) – Bbus(i, 🙂 * cos(theta(i) – theta))) == 0];
else
constraints = [constraints, -Pd(i) – V(i) * sum(V * (Gbus(i, 🙂 * cos(theta(i) – theta) + Bbus(i, 🙂 * sin(theta(i) – theta))) == 0];
constraints = [constraints, -Qd(i) + V(i) * sum(V * (Gbus(i, 🙂 * sin(theta(i) – theta) – Bbus(i, 🙂 * cos(theta(i) – theta))) == 0];
end
end
% Generator output limit constraints
for i = 1:ng
% Minimum active power output constraint for generator i
constraints = [constraints, Pgmin(i) <= Pg(i)];
% Maximum active power output constraint for generator i
constraints = [constraints, Pg(i) <= Pgmax(i)];
% Minimum reactive power output constraint for generator i
constraints = [constraints, Qgmin(i) <= Qg(i)];
% Maximum reactive power output constraint for generator i
constraints = [constraints, Qg(i) <= Qgmax(i)];
end
% Bus voltage limit constraints
for i = 1:nb
% Minimum bus voltage magnitude constraint for bus i
constraints = [constraints, Vmin(i) <= V(i)];
% Maximum bus voltage magnitude constraint for bus i
constraints = [constraints, V(i) <= Vmax(i)];
end
% Branch power flow limit constraints
for i = 1:nl
% Calculate active power flow on branch i (assuming the "from" bus is the positive direction)
Pl(i) = V(fbus(i))^2 * Gbus(fbus(i), tbus(i)) – V(fbus(i)) * V(tbus(i)) * (Gbus(fbus(i), tbus(i)) * cos(theta(fbus(i) – theta(tbus(i))) + Bbus(fbus(i), tbus(i)) * sin(theta(fbus(i) – theta(tbus(i)))));
% Absolute value constraint for active power flow on branch i
constraints = [constraints, abs(Pl(i)) <= Plmax(i)];
end
% Solve the optimal power flow problem
result = solvesdp(constraints, objective); % Use YALMIP to solve the optimal power flow problem
% Output and analyze the results
if result.problem == 0 % If the solution is successful
disp(‘Optimal Power Flow Solved Successfully!’); % Display success message
disp(‘Total System Operating Cost:’); % Display total system operating cost
value(objective) % Display the objective function value
disp(‘Generator Active Power Output:’); % Display generator active power output
value(Pg) % Display the generator active power output variable values
disp(‘Generator Reactive Power Output:’); % Display generator reactive power output
value(Qg) % Display the generator reactive power output variable values
disp(‘Bus Voltage Magnitude:’); % Display bus voltage magnitude
value(V) % Display the bus voltage magnitude variable values
disp(‘Bus Voltage Angle (in degrees):’); % Display bus voltage angle (in degrees)
rad2deg(value(theta)) % Display bus voltage angle variable values and convert to degrees
disp(‘Branch Active Power Flow:’); % Display branch active power flow
value(Pl)
end I use MATLAB-YALMIP to write the optimal trend program based on the IEEEE14 system, but I can’t converge. Please help to see if the program is wrong?
code:
% Optimal Power Flow Example
% Based on the IEEE 14-bus standard case (i.e., case14 in Matpower)
% Implemented in MATLAB with YALMIP
clear; clc;
% Load power system data
mpc = loadcase(‘case14’); % You can also load other data files, such as case9, case30, etc.
% Define variables and parameters
nb = size(mpc.bus, 1); % Number of buses (nodes)
nl = size(mpc.branch, 1); % Number of branches (lines)
ng = size(mpc.gen, 1); % Number of generators
nr = nb – ng; % Number of load buses
% Extract node data
bus_id = mpc.bus(:, 1); % Bus IDs
bus_type = mpc.bus(:, 2); % Bus types (1-PQ, 2-PV, 3-Slack)
Pd = mpc.bus(:, 3); % Active power demand (MW)
Qd = mpc.bus(:, 4); % Reactive power demand (MVAr)
Vmin = mpc.bus(:, 13); % Minimum bus voltage (p.u.)
Vmax = mpc.bus(:, 12); % Maximum bus voltage (p.u.)
% Extract generator data
gen_id = mpc.gen(:, 1); % Bus IDs where generators are connected
Pgmin = mpc.gen(:, 10); % Minimum generator active power output (MW)
Pgmax = mpc.gen(:, 9); % Maximum generator active power output (MW)
Qgmin = mpc.gen(:, 5); % Minimum generator reactive power output (MVAr)
Qgmax = mpc.gen(:, 4); % Maximum generator reactive power output (MVAr)
a2 = mpc.gencost(:, 5); % Generator cost curve coefficient for quadratic term
a1 = mpc.gencost(:, 6); % Generator cost curve coefficient for linear term
a0 = mpc.gencost(:, 7); % Generator cost curve constant term
% Extract branch data
fbus = mpc.branch(:, 1); % "From" bus (starting node) of each branch
tbus = mpc.branch(:, 2); % "To" bus (ending node) of each branch
Plmax = ones(nl, 1) * 4000; % Maximum branch active power flow limit (MW)
% Plmax = mpc.branch(:, 6) .* mpc.branch(:, 3) * 1e-3; % Maximum branch active power flow limit (MW)
% Calculate the bus admittance matrix
[Ybus, ~, ~] = makeYbus(mpc); % Use a Matpower function to calculate the bus admittance matrix
Gbus = real(Ybus); % Real part of bus admittance matrix (conductance)
Bbus = imag(Ybus); % Imaginary part of bus admittance matrix (susceptance)
% Define YALMIP variables
Pg = sdpvar(ng, 1, ‘full’); % Generator active power output variables
Qg = sdpvar(ng, 1, ‘full’); % Generator reactive power output variables
V = sdpvar(nb, 1, ‘full’); % Bus voltage magnitude variables
theta = sdpvar(nb, 1, ‘full’); % Bus voltage angle variables
Pl = sdpvar(nl, 1, ‘full’); % Branch active power flow variables
% Define the objective function
objective = sum(a2 .* Pg.^2 + a1 .* Pg + a0); % Minimize the total operating cost
% Define constraints
constraints = [];
% Node power balance constraints
for i = 1:nb
% Active power balance equation for node i
if ismember(i, gen_id)
record = find(gen_id == i);
constraints = [constraints, Pg(record) – Pd(i) – V(i) * sum(V * (Gbus(i, 🙂 * cos(theta(i) – theta) + Bbus(i, 🙂 * sin(theta(i) – theta))) == 0];
constraints = [constraints, Qg(record) – Qd(i) + V(i) * sum(V * (Gbus(i, 🙂 * sin(theta(i) – theta) – Bbus(i, 🙂 * cos(theta(i) – theta))) == 0];
else
constraints = [constraints, -Pd(i) – V(i) * sum(V * (Gbus(i, 🙂 * cos(theta(i) – theta) + Bbus(i, 🙂 * sin(theta(i) – theta))) == 0];
constraints = [constraints, -Qd(i) + V(i) * sum(V * (Gbus(i, 🙂 * sin(theta(i) – theta) – Bbus(i, 🙂 * cos(theta(i) – theta))) == 0];
end
end
% Generator output limit constraints
for i = 1:ng
% Minimum active power output constraint for generator i
constraints = [constraints, Pgmin(i) <= Pg(i)];
% Maximum active power output constraint for generator i
constraints = [constraints, Pg(i) <= Pgmax(i)];
% Minimum reactive power output constraint for generator i
constraints = [constraints, Qgmin(i) <= Qg(i)];
% Maximum reactive power output constraint for generator i
constraints = [constraints, Qg(i) <= Qgmax(i)];
end
% Bus voltage limit constraints
for i = 1:nb
% Minimum bus voltage magnitude constraint for bus i
constraints = [constraints, Vmin(i) <= V(i)];
% Maximum bus voltage magnitude constraint for bus i
constraints = [constraints, V(i) <= Vmax(i)];
end
% Branch power flow limit constraints
for i = 1:nl
% Calculate active power flow on branch i (assuming the "from" bus is the positive direction)
Pl(i) = V(fbus(i))^2 * Gbus(fbus(i), tbus(i)) – V(fbus(i)) * V(tbus(i)) * (Gbus(fbus(i), tbus(i)) * cos(theta(fbus(i) – theta(tbus(i))) + Bbus(fbus(i), tbus(i)) * sin(theta(fbus(i) – theta(tbus(i)))));
% Absolute value constraint for active power flow on branch i
constraints = [constraints, abs(Pl(i)) <= Plmax(i)];
end
% Solve the optimal power flow problem
result = solvesdp(constraints, objective); % Use YALMIP to solve the optimal power flow problem
% Output and analyze the results
if result.problem == 0 % If the solution is successful
disp(‘Optimal Power Flow Solved Successfully!’); % Display success message
disp(‘Total System Operating Cost:’); % Display total system operating cost
value(objective) % Display the objective function value
disp(‘Generator Active Power Output:’); % Display generator active power output
value(Pg) % Display the generator active power output variable values
disp(‘Generator Reactive Power Output:’); % Display generator reactive power output
value(Qg) % Display the generator reactive power output variable values
disp(‘Bus Voltage Magnitude:’); % Display bus voltage magnitude
value(V) % Display the bus voltage magnitude variable values
disp(‘Bus Voltage Angle (in degrees):’); % Display bus voltage angle (in degrees)
rad2deg(value(theta)) % Display bus voltage angle variable values and convert to degrees
disp(‘Branch Active Power Flow:’); % Display branch active power flow
value(Pl)
end yalmip, opf, matlab, optimal power flow MATLAB Answers — New Questions
‘mcc’ ignoring “-w disable” option
I’m using a Makefile (on Linux) to call ‘mcc’ (R2017b) to compile multiple projects. I’ve added the "-w disable" option, and when ‘make’ prints out the command line, the option is there. But the console output still contains warning messages. Am I missing or not correctly understanding something?
In case it’s important, the specific warning I really want to suppress is MATLAB:depfun:req:CorrespondingMCodeIsEmpty. There are 1000s of lines of console output for this warning type, but I know everything compiles and works fine. So I want to improve my odds of catching any other warnings that might show up. Trying to disable just that one warning wasn’t working, so I tried to disable all warnings and discovered this problem.
Again, in case it’s important, these warnings are being triggered by P-code files that are being brought in via a "-a" specification.
The full command line being issued by ‘make’ is like:
cd mcc/linux && /path/to/mcc -R -nodesktop -m -v -w disable -a /path/to/pcode -a /another/path/to/pcode /path/to/source.p
All assistance appreciated!I’m using a Makefile (on Linux) to call ‘mcc’ (R2017b) to compile multiple projects. I’ve added the "-w disable" option, and when ‘make’ prints out the command line, the option is there. But the console output still contains warning messages. Am I missing or not correctly understanding something?
In case it’s important, the specific warning I really want to suppress is MATLAB:depfun:req:CorrespondingMCodeIsEmpty. There are 1000s of lines of console output for this warning type, but I know everything compiles and works fine. So I want to improve my odds of catching any other warnings that might show up. Trying to disable just that one warning wasn’t working, so I tried to disable all warnings and discovered this problem.
Again, in case it’s important, these warnings are being triggered by P-code files that are being brought in via a "-a" specification.
The full command line being issued by ‘make’ is like:
cd mcc/linux && /path/to/mcc -R -nodesktop -m -v -w disable -a /path/to/pcode -a /another/path/to/pcode /path/to/source.p
All assistance appreciated! I’m using a Makefile (on Linux) to call ‘mcc’ (R2017b) to compile multiple projects. I’ve added the "-w disable" option, and when ‘make’ prints out the command line, the option is there. But the console output still contains warning messages. Am I missing or not correctly understanding something?
In case it’s important, the specific warning I really want to suppress is MATLAB:depfun:req:CorrespondingMCodeIsEmpty. There are 1000s of lines of console output for this warning type, but I know everything compiles and works fine. So I want to improve my odds of catching any other warnings that might show up. Trying to disable just that one warning wasn’t working, so I tried to disable all warnings and discovered this problem.
Again, in case it’s important, these warnings are being triggered by P-code files that are being brought in via a "-a" specification.
The full command line being issued by ‘make’ is like:
cd mcc/linux && /path/to/mcc -R -nodesktop -m -v -w disable -a /path/to/pcode -a /another/path/to/pcode /path/to/source.p
All assistance appreciated! matlab compiler, linux, mcc, makefile, disable warnings MATLAB Answers — New Questions
Is there a way to use the Vehicle 6DOF block with steering angle and wheel speed as inputs?
The 3 DOF Vehicle Body Block supports steering angle and wheel speed as inputs, but the 6 DOF Vehicle Body Block only seems to support suspension and external forces and moments as inputs.
Is there a way to use the 6 DOF block with steering angle and wheel speed control inputs, and perhaps an additional environment input? I know the Constant Radius Reference Application uses the 6DOF block under the hood, but this is a huge step up in complexity from the 2-dimensional 3DOF block. Looking to make the jump from 2-D to 3-D, but preferably still using typical control inputs.The 3 DOF Vehicle Body Block supports steering angle and wheel speed as inputs, but the 6 DOF Vehicle Body Block only seems to support suspension and external forces and moments as inputs.
Is there a way to use the 6 DOF block with steering angle and wheel speed control inputs, and perhaps an additional environment input? I know the Constant Radius Reference Application uses the 6DOF block under the hood, but this is a huge step up in complexity from the 2-dimensional 3DOF block. Looking to make the jump from 2-D to 3-D, but preferably still using typical control inputs. The 3 DOF Vehicle Body Block supports steering angle and wheel speed as inputs, but the 6 DOF Vehicle Body Block only seems to support suspension and external forces and moments as inputs.
Is there a way to use the 6 DOF block with steering angle and wheel speed control inputs, and perhaps an additional environment input? I know the Constant Radius Reference Application uses the 6DOF block under the hood, but this is a huge step up in complexity from the 2-dimensional 3DOF block. Looking to make the jump from 2-D to 3-D, but preferably still using typical control inputs. vehicle dynamics, 6dof, simulink MATLAB Answers — New Questions
A few basic Simulink/Simscape questions
In the past I’ve generally used Simulink simulations for short bursts of transient analysis.
I was curious if it were possible to use it more like LabView, where a simulation can also run forever (tstop = inf), and you can interact with and modify the setup in run time by pushing buttons (opening and closing SimScape circuits).
Regarding memory, I would not want to store all time data. It would be good to store the trailing 10000 points. I’m not sure how to do that either.In the past I’ve generally used Simulink simulations for short bursts of transient analysis.
I was curious if it were possible to use it more like LabView, where a simulation can also run forever (tstop = inf), and you can interact with and modify the setup in run time by pushing buttons (opening and closing SimScape circuits).
Regarding memory, I would not want to store all time data. It would be good to store the trailing 10000 points. I’m not sure how to do that either. In the past I’ve generally used Simulink simulations for short bursts of transient analysis.
I was curious if it were possible to use it more like LabView, where a simulation can also run forever (tstop = inf), and you can interact with and modify the setup in run time by pushing buttons (opening and closing SimScape circuits).
Regarding memory, I would not want to store all time data. It would be good to store the trailing 10000 points. I’m not sure how to do that either. simulink, simscape, interactive buttons, memory MATLAB Answers — New Questions