Category: Matlab
Category Archives: Matlab
Size of the left side different from the right side
Hi everyone, I’m facing a problem with assignment because of different sizes.
I’m pretty sure the sizes are the same, its look like MATLAB refer to the input size instead of the output (in the relevant function).
the error massege: "Unable to perform assignment because the size of the left side is 1-by-6 and the size of the right side
is 1-by-108".
thanks a lot!
the problematic line:
[PersonalSPQmain(i,:),PersonalSPAnsmain(i,:)] = PersonalSPQforResponder(SParraydata(i,:));
My code -main function:
SParraydata=table2array(SPdata);
personalSPdata=zeros(51444,2);
PersonalSPQmain=zeros(8574,6);
PersonalSPAnsmain=zeros(8574,6);
j=1;
for i=1:8574
[PersonalSPQmain(i,:),PersonalSPAnsmain(i,:)] = PersonalSPQforResponder(SParraydata(i,:));
personalSPdata(j:j+5,2) = sixSPAnsLines(PersonalSPQmain(i,:),PersonalSPAnsmain(i,:));
j=j+5;
end
The relevent function:
function [PersonalSPQ,PersonalSPAns] = PersonalSPQforResponder(SPAnsVector)
PersonalSPQ=zeros(1,6);
PersonalSPAns=zeros(1,6);
j=1;
for i=1:108
if isempty(SPAnsVector(1,i))==0
PersonalSPQ(1,j)=i;
PersonalSPAns(1,j)=SPAnsVector(1,i);
j=j+1;
end
end
endHi everyone, I’m facing a problem with assignment because of different sizes.
I’m pretty sure the sizes are the same, its look like MATLAB refer to the input size instead of the output (in the relevant function).
the error massege: "Unable to perform assignment because the size of the left side is 1-by-6 and the size of the right side
is 1-by-108".
thanks a lot!
the problematic line:
[PersonalSPQmain(i,:),PersonalSPAnsmain(i,:)] = PersonalSPQforResponder(SParraydata(i,:));
My code -main function:
SParraydata=table2array(SPdata);
personalSPdata=zeros(51444,2);
PersonalSPQmain=zeros(8574,6);
PersonalSPAnsmain=zeros(8574,6);
j=1;
for i=1:8574
[PersonalSPQmain(i,:),PersonalSPAnsmain(i,:)] = PersonalSPQforResponder(SParraydata(i,:));
personalSPdata(j:j+5,2) = sixSPAnsLines(PersonalSPQmain(i,:),PersonalSPAnsmain(i,:));
j=j+5;
end
The relevent function:
function [PersonalSPQ,PersonalSPAns] = PersonalSPQforResponder(SPAnsVector)
PersonalSPQ=zeros(1,6);
PersonalSPAns=zeros(1,6);
j=1;
for i=1:108
if isempty(SPAnsVector(1,i))==0
PersonalSPQ(1,j)=i;
PersonalSPAns(1,j)=SPAnsVector(1,i);
j=j+1;
end
end
end Hi everyone, I’m facing a problem with assignment because of different sizes.
I’m pretty sure the sizes are the same, its look like MATLAB refer to the input size instead of the output (in the relevant function).
the error massege: "Unable to perform assignment because the size of the left side is 1-by-6 and the size of the right side
is 1-by-108".
thanks a lot!
the problematic line:
[PersonalSPQmain(i,:),PersonalSPAnsmain(i,:)] = PersonalSPQforResponder(SParraydata(i,:));
My code -main function:
SParraydata=table2array(SPdata);
personalSPdata=zeros(51444,2);
PersonalSPQmain=zeros(8574,6);
PersonalSPAnsmain=zeros(8574,6);
j=1;
for i=1:8574
[PersonalSPQmain(i,:),PersonalSPAnsmain(i,:)] = PersonalSPQforResponder(SParraydata(i,:));
personalSPdata(j:j+5,2) = sixSPAnsLines(PersonalSPQmain(i,:),PersonalSPAnsmain(i,:));
j=j+5;
end
The relevent function:
function [PersonalSPQ,PersonalSPAns] = PersonalSPQforResponder(SPAnsVector)
PersonalSPQ=zeros(1,6);
PersonalSPAns=zeros(1,6);
j=1;
for i=1:108
if isempty(SPAnsVector(1,i))==0
PersonalSPQ(1,j)=i;
PersonalSPAns(1,j)=SPAnsVector(1,i);
j=j+1;
end
end
end size, assigment, error MATLAB Answers — New Questions
MATLAB Arduino Uno Simulink doesn’t have option for Connected IO Mode
Hello;
I’m trying to use Simulink to get input from Beckhoff TwinCAT (reading an EtherCAT sensor) and then output it to an Arduino as a set of PWM waves (to control some coil currents). To do this, I’m trying to link the TwinCAT integration to the Simulink Support Package for Arduino Hardware on MATLAB R2021a on a laptop running MATLAB R2021a; however, I don’t see the option to switch the mode to Connected IO in the top Hardware bar. I have tried enabling Connected IO in the hardware settings for the Arduino Uno on Simulink, but the option is still not showing up.
Is there something else I am missing?Hello;
I’m trying to use Simulink to get input from Beckhoff TwinCAT (reading an EtherCAT sensor) and then output it to an Arduino as a set of PWM waves (to control some coil currents). To do this, I’m trying to link the TwinCAT integration to the Simulink Support Package for Arduino Hardware on MATLAB R2021a on a laptop running MATLAB R2021a; however, I don’t see the option to switch the mode to Connected IO in the top Hardware bar. I have tried enabling Connected IO in the hardware settings for the Arduino Uno on Simulink, but the option is still not showing up.
Is there something else I am missing? Hello;
I’m trying to use Simulink to get input from Beckhoff TwinCAT (reading an EtherCAT sensor) and then output it to an Arduino as a set of PWM waves (to control some coil currents). To do this, I’m trying to link the TwinCAT integration to the Simulink Support Package for Arduino Hardware on MATLAB R2021a on a laptop running MATLAB R2021a; however, I don’t see the option to switch the mode to Connected IO in the top Hardware bar. I have tried enabling Connected IO in the hardware settings for the Arduino Uno on Simulink, but the option is still not showing up.
Is there something else I am missing? r2021a, simulink, arduino MATLAB Answers — New Questions
readtable struggling to interpret spreadsheet as numbers
Hi folks,
I’m trying to use the readtable function to interpret a spreadsheet "Alberta.csv". I’ve tried using detectImportOpts, sadly the variables are arranged in rows and readtable seems to want to detect them as columns.
The next attempt was as follows:
seriesAL = table2dataset(rows2vars(readtable("Alberta.csv", ReadRowNames=1, MissingRule="omitrow")));
or
seriesAL = table2array(rows2vars(readtable("Alberta.csv", ReadRowNames=1, MissingRule="omitrow")));
then if I try to complete an operation:
rgdp_AL = log(0.001 .* seriesAL{:,40})
Matlab tells me I’m using too many input arguments… If I enter:
seriesAL(:,40), I’m failing to get numbers, yet seriesAL{} doesn’t want to provide the full column of values!
I’m getting very confused by the way Matlab uses tables, cells, structs, etc… Can anyone help me get numbers?Hi folks,
I’m trying to use the readtable function to interpret a spreadsheet "Alberta.csv". I’ve tried using detectImportOpts, sadly the variables are arranged in rows and readtable seems to want to detect them as columns.
The next attempt was as follows:
seriesAL = table2dataset(rows2vars(readtable("Alberta.csv", ReadRowNames=1, MissingRule="omitrow")));
or
seriesAL = table2array(rows2vars(readtable("Alberta.csv", ReadRowNames=1, MissingRule="omitrow")));
then if I try to complete an operation:
rgdp_AL = log(0.001 .* seriesAL{:,40})
Matlab tells me I’m using too many input arguments… If I enter:
seriesAL(:,40), I’m failing to get numbers, yet seriesAL{} doesn’t want to provide the full column of values!
I’m getting very confused by the way Matlab uses tables, cells, structs, etc… Can anyone help me get numbers? Hi folks,
I’m trying to use the readtable function to interpret a spreadsheet "Alberta.csv". I’ve tried using detectImportOpts, sadly the variables are arranged in rows and readtable seems to want to detect them as columns.
The next attempt was as follows:
seriesAL = table2dataset(rows2vars(readtable("Alberta.csv", ReadRowNames=1, MissingRule="omitrow")));
or
seriesAL = table2array(rows2vars(readtable("Alberta.csv", ReadRowNames=1, MissingRule="omitrow")));
then if I try to complete an operation:
rgdp_AL = log(0.001 .* seriesAL{:,40})
Matlab tells me I’m using too many input arguments… If I enter:
seriesAL(:,40), I’m failing to get numbers, yet seriesAL{} doesn’t want to provide the full column of values!
I’m getting very confused by the way Matlab uses tables, cells, structs, etc… Can anyone help me get numbers? readtable, struct MATLAB Answers — New Questions
find best fit ellipse to a set of data points
I’m new to matlab so I don’t know how to use it that well yet; however, I have to find the best fit ellipse for a set of data points I have for a project and I’ve been struggling to find a code that would help me do this. Does anyone know what code I could use? Thanks for your help!I’m new to matlab so I don’t know how to use it that well yet; however, I have to find the best fit ellipse for a set of data points I have for a project and I’ve been struggling to find a code that would help me do this. Does anyone know what code I could use? Thanks for your help! I’m new to matlab so I don’t know how to use it that well yet; however, I have to find the best fit ellipse for a set of data points I have for a project and I’ve been struggling to find a code that would help me do this. Does anyone know what code I could use? Thanks for your help! best fit, ellipse, curve fitting MATLAB Answers — New Questions
Multilayer Perceptron with More Than One Output and Data Interpretation?
I haven’t used Matlab’s ML or deep learning toolbox since maybe 2022. In the last year, it seems like MathWorks intentionally made the ML portion of Matlab unusable. I’m hoping someone here can help me out because rolling back my matlab two years will make a lot of my recent work unstable. I’ve done my best to document my process here. Error messages are given in italics for ease of reading.
I have some data that is represented by four doubles that are normalzied to between 0 and 1. I would like to use these four doubles to predict two doubles that are also between 0 and 1. I would like to make a multilayer perceptron that will take in the four values and spit out the two values. However, createMLPNetwork doesn’t appear to support multiple outputs – at least, the documentation for it doesn’t explain how to do so. So I have tried to make a MLP from scratch using the following code:
%% Prep NN architecture
layers = [
inputLayer([4, 1], "CU", name="in")
flattenLayer
fullyConnectedLayer(20, name="fc1")
reluLayer
fullyConnectedLayerB(16, name="fc2")
reluLayer
fullyConnectedLayer(12, name="fc3")
reluLayer
fullyConnectedLayer(numel(data{1,1}), name="output")
softmaxLayer
];
net = dlnetwork(layers);
[trainedNet, info] = trainnet(train, layers, "mse", opts);
Attempting to run this gives me the following results:
Error using trainnet (line 46)
Error forming mini-batch for network input "in". Data interpreted with format "CU". To specify a different format, use the InputDataFormats option.
Error in trainRutileModel (line 107)
[trainedNet, info] = trainnet(train, layers, "mse", opts);
Caused by:
The data format must have a batch dimension.
I tried to get around using the generic inputLayer function by using the more specific functions like featureInputLayer but replacing the inputLayer with a featureInputLayer throws the following:
Error using trainnet (line 46)
Number of observations in predictors (4) and targets (2) must match. Check that the data and network are consistent.
Error in trainRutileModel (line 107)
[trainedNet, info] = trainnet(train, layers, "mse", opts);
So that won’t work because I only have two output data points. The same happened when I tried imageInputLayer. Then I tried replacing "CU" with other values – the following error is for "BU" but the other errors are the same – but got the following:
Error using dlnetwork/initialize (line 558)
Invalid network.
Error in dlnetwork (line 167)
net = initialize(net, dlX{:});
Error in trainRutileModel (line 104)
net = dlnetwork(layers);
Caused by:
Layer ‘fc1’: Invalid input data for fully connected layer. The input data must have exactly one channel dimension.
So then I tried flattening the output and got the following error:
Error using dlnetwork/initialize (line 558)
Invalid network.
Error in dlnetwork (line 167)
net = initialize(net, dlX{:});
Error in trainRutileModel (line 105)
net = dlnetwork(layers);
Caused by:
Layer ‘flatten’: Invalid input data. Layer expects data with a channel dimension, but received input data with format "BU".
I’m really not sure what to do here. I have no idea why MathWorks would make this so much more difficult to use and give so much less, and more opaque, documentation. If anyone has any ideas on how to make this work, I’d be happy to hear them. In the meantime, I’m going to take another crack at the createMLPNetwork function and hope that when MathWorks says "a black-box continuous-time or discrete-time neural state-space model with identifiable (estimable) network weights and bias," by "states" they mean "outputs."I haven’t used Matlab’s ML or deep learning toolbox since maybe 2022. In the last year, it seems like MathWorks intentionally made the ML portion of Matlab unusable. I’m hoping someone here can help me out because rolling back my matlab two years will make a lot of my recent work unstable. I’ve done my best to document my process here. Error messages are given in italics for ease of reading.
I have some data that is represented by four doubles that are normalzied to between 0 and 1. I would like to use these four doubles to predict two doubles that are also between 0 and 1. I would like to make a multilayer perceptron that will take in the four values and spit out the two values. However, createMLPNetwork doesn’t appear to support multiple outputs – at least, the documentation for it doesn’t explain how to do so. So I have tried to make a MLP from scratch using the following code:
%% Prep NN architecture
layers = [
inputLayer([4, 1], "CU", name="in")
flattenLayer
fullyConnectedLayer(20, name="fc1")
reluLayer
fullyConnectedLayerB(16, name="fc2")
reluLayer
fullyConnectedLayer(12, name="fc3")
reluLayer
fullyConnectedLayer(numel(data{1,1}), name="output")
softmaxLayer
];
net = dlnetwork(layers);
[trainedNet, info] = trainnet(train, layers, "mse", opts);
Attempting to run this gives me the following results:
Error using trainnet (line 46)
Error forming mini-batch for network input "in". Data interpreted with format "CU". To specify a different format, use the InputDataFormats option.
Error in trainRutileModel (line 107)
[trainedNet, info] = trainnet(train, layers, "mse", opts);
Caused by:
The data format must have a batch dimension.
I tried to get around using the generic inputLayer function by using the more specific functions like featureInputLayer but replacing the inputLayer with a featureInputLayer throws the following:
Error using trainnet (line 46)
Number of observations in predictors (4) and targets (2) must match. Check that the data and network are consistent.
Error in trainRutileModel (line 107)
[trainedNet, info] = trainnet(train, layers, "mse", opts);
So that won’t work because I only have two output data points. The same happened when I tried imageInputLayer. Then I tried replacing "CU" with other values – the following error is for "BU" but the other errors are the same – but got the following:
Error using dlnetwork/initialize (line 558)
Invalid network.
Error in dlnetwork (line 167)
net = initialize(net, dlX{:});
Error in trainRutileModel (line 104)
net = dlnetwork(layers);
Caused by:
Layer ‘fc1’: Invalid input data for fully connected layer. The input data must have exactly one channel dimension.
So then I tried flattening the output and got the following error:
Error using dlnetwork/initialize (line 558)
Invalid network.
Error in dlnetwork (line 167)
net = initialize(net, dlX{:});
Error in trainRutileModel (line 105)
net = dlnetwork(layers);
Caused by:
Layer ‘flatten’: Invalid input data. Layer expects data with a channel dimension, but received input data with format "BU".
I’m really not sure what to do here. I have no idea why MathWorks would make this so much more difficult to use and give so much less, and more opaque, documentation. If anyone has any ideas on how to make this work, I’d be happy to hear them. In the meantime, I’m going to take another crack at the createMLPNetwork function and hope that when MathWorks says "a black-box continuous-time or discrete-time neural state-space model with identifiable (estimable) network weights and bias," by "states" they mean "outputs." I haven’t used Matlab’s ML or deep learning toolbox since maybe 2022. In the last year, it seems like MathWorks intentionally made the ML portion of Matlab unusable. I’m hoping someone here can help me out because rolling back my matlab two years will make a lot of my recent work unstable. I’ve done my best to document my process here. Error messages are given in italics for ease of reading.
I have some data that is represented by four doubles that are normalzied to between 0 and 1. I would like to use these four doubles to predict two doubles that are also between 0 and 1. I would like to make a multilayer perceptron that will take in the four values and spit out the two values. However, createMLPNetwork doesn’t appear to support multiple outputs – at least, the documentation for it doesn’t explain how to do so. So I have tried to make a MLP from scratch using the following code:
%% Prep NN architecture
layers = [
inputLayer([4, 1], "CU", name="in")
flattenLayer
fullyConnectedLayer(20, name="fc1")
reluLayer
fullyConnectedLayerB(16, name="fc2")
reluLayer
fullyConnectedLayer(12, name="fc3")
reluLayer
fullyConnectedLayer(numel(data{1,1}), name="output")
softmaxLayer
];
net = dlnetwork(layers);
[trainedNet, info] = trainnet(train, layers, "mse", opts);
Attempting to run this gives me the following results:
Error using trainnet (line 46)
Error forming mini-batch for network input "in". Data interpreted with format "CU". To specify a different format, use the InputDataFormats option.
Error in trainRutileModel (line 107)
[trainedNet, info] = trainnet(train, layers, "mse", opts);
Caused by:
The data format must have a batch dimension.
I tried to get around using the generic inputLayer function by using the more specific functions like featureInputLayer but replacing the inputLayer with a featureInputLayer throws the following:
Error using trainnet (line 46)
Number of observations in predictors (4) and targets (2) must match. Check that the data and network are consistent.
Error in trainRutileModel (line 107)
[trainedNet, info] = trainnet(train, layers, "mse", opts);
So that won’t work because I only have two output data points. The same happened when I tried imageInputLayer. Then I tried replacing "CU" with other values – the following error is for "BU" but the other errors are the same – but got the following:
Error using dlnetwork/initialize (line 558)
Invalid network.
Error in dlnetwork (line 167)
net = initialize(net, dlX{:});
Error in trainRutileModel (line 104)
net = dlnetwork(layers);
Caused by:
Layer ‘fc1’: Invalid input data for fully connected layer. The input data must have exactly one channel dimension.
So then I tried flattening the output and got the following error:
Error using dlnetwork/initialize (line 558)
Invalid network.
Error in dlnetwork (line 167)
net = initialize(net, dlX{:});
Error in trainRutileModel (line 105)
net = dlnetwork(layers);
Caused by:
Layer ‘flatten’: Invalid input data. Layer expects data with a channel dimension, but received input data with format "BU".
I’m really not sure what to do here. I have no idea why MathWorks would make this so much more difficult to use and give so much less, and more opaque, documentation. If anyone has any ideas on how to make this work, I’d be happy to hear them. In the meantime, I’m going to take another crack at the createMLPNetwork function and hope that when MathWorks says "a black-box continuous-time or discrete-time neural state-space model with identifiable (estimable) network weights and bias," by "states" they mean "outputs." multilayer perceptron, mlp, neural network, inputlayer MATLAB Answers — New Questions
Determine the indice of real maximum using accumarray function
I’m doing signal analysis on the peaks and valleys of a sinusoidal signal. Using accumarray has been quite effective at determining the extrema, but I’m seriously struggling with what should be a simple part of my implementation. Currently the returned peakLoc values are not integer timesteps, but a decimal average of all the timesteps that are considered part of the peak. The only new functionality I need is to get the real integer timestep for the highest (or lowest) extrema. Whether there is an option for the single accumarray line with @mean or another way, I don’t care. Over the past three days I have been slopping together different nested loops to try to pin down the behavior I want and I’m sure there’s got to be a simple way to accomplish this.
I’m sure there’s a lot of other ways I could improve this code, but I just need it working. I’m not experienced and constantly bang my head against indexing problems (whether mixing up dimension, logical indexing oddities, etc.) and other beginner problems.
function [peakLoc, peakVal] = getExtrema(durThreshold, PEThreshold, gettingMax, PEAverage, timestep)
% Gets passed duration (# of consecutive timesteps above zero) and PE threshold (0).
% Returns the timestep and PE value for all of Maximum or of Minimum extrema.
if gettingMax == true
isPeak = PEAverage > PEThreshold;
else
isPeak = PEAverage < PEThreshold;
end
CC = bwconncomp(isPeak);
peakID = labelmatrix(CC);
peakLabel = unique(peakID);
peakSize = accumarray(peakID(:)+1,1);
peakSize(1) = 0; % set the # of <0 elements to 0
realPeakLabels = peakLabel(peakSize >= durThreshold);
isRealPeak = ismember(peakID,realPeakLabels);
% Now find the max in the real peaks (realPeakLabels?), accumarray will help
peakID(~isRealPeak) = 0;
if gettingMax == true
peakVal = accumarray(peakID(:)+1,PEAverage(:),[numel(peakSize) 1],@max,NaN);
else
peakVal = accumarray(peakID(:)+1,PEAverage(:),[numel(peakSize) 1],@min,NaN);
end
%% Get the right peakLoc, not the @mean
% @mean is approximation of the timestep where the real peak value occurs
peakLoc = accumarray(peakID(:)+1,timestep(:),[numel(peakSize) 1],@mean,NaN);
peakLoc = zeros(length(peakLabel),1);
j = 1;
for i = timestep
% Get the right index
if peakID(i) > j
j = peakID(i);
end
if ismember(j, realPeakLabels)
if gettingMax == true
if PEAverage(i) > peakVal(j)
peakLoc(j) = timestep(i);
end
else
if PEAverage(i) < peakVal(j)
peakLoc(j) = timestep(i);
end
end
end
end
peakVal(1) = NaN;
peakLoc(peakLoc == 0) = NaN;
endI’m doing signal analysis on the peaks and valleys of a sinusoidal signal. Using accumarray has been quite effective at determining the extrema, but I’m seriously struggling with what should be a simple part of my implementation. Currently the returned peakLoc values are not integer timesteps, but a decimal average of all the timesteps that are considered part of the peak. The only new functionality I need is to get the real integer timestep for the highest (or lowest) extrema. Whether there is an option for the single accumarray line with @mean or another way, I don’t care. Over the past three days I have been slopping together different nested loops to try to pin down the behavior I want and I’m sure there’s got to be a simple way to accomplish this.
I’m sure there’s a lot of other ways I could improve this code, but I just need it working. I’m not experienced and constantly bang my head against indexing problems (whether mixing up dimension, logical indexing oddities, etc.) and other beginner problems.
function [peakLoc, peakVal] = getExtrema(durThreshold, PEThreshold, gettingMax, PEAverage, timestep)
% Gets passed duration (# of consecutive timesteps above zero) and PE threshold (0).
% Returns the timestep and PE value for all of Maximum or of Minimum extrema.
if gettingMax == true
isPeak = PEAverage > PEThreshold;
else
isPeak = PEAverage < PEThreshold;
end
CC = bwconncomp(isPeak);
peakID = labelmatrix(CC);
peakLabel = unique(peakID);
peakSize = accumarray(peakID(:)+1,1);
peakSize(1) = 0; % set the # of <0 elements to 0
realPeakLabels = peakLabel(peakSize >= durThreshold);
isRealPeak = ismember(peakID,realPeakLabels);
% Now find the max in the real peaks (realPeakLabels?), accumarray will help
peakID(~isRealPeak) = 0;
if gettingMax == true
peakVal = accumarray(peakID(:)+1,PEAverage(:),[numel(peakSize) 1],@max,NaN);
else
peakVal = accumarray(peakID(:)+1,PEAverage(:),[numel(peakSize) 1],@min,NaN);
end
%% Get the right peakLoc, not the @mean
% @mean is approximation of the timestep where the real peak value occurs
peakLoc = accumarray(peakID(:)+1,timestep(:),[numel(peakSize) 1],@mean,NaN);
peakLoc = zeros(length(peakLabel),1);
j = 1;
for i = timestep
% Get the right index
if peakID(i) > j
j = peakID(i);
end
if ismember(j, realPeakLabels)
if gettingMax == true
if PEAverage(i) > peakVal(j)
peakLoc(j) = timestep(i);
end
else
if PEAverage(i) < peakVal(j)
peakLoc(j) = timestep(i);
end
end
end
end
peakVal(1) = NaN;
peakLoc(peakLoc == 0) = NaN;
end I’m doing signal analysis on the peaks and valleys of a sinusoidal signal. Using accumarray has been quite effective at determining the extrema, but I’m seriously struggling with what should be a simple part of my implementation. Currently the returned peakLoc values are not integer timesteps, but a decimal average of all the timesteps that are considered part of the peak. The only new functionality I need is to get the real integer timestep for the highest (or lowest) extrema. Whether there is an option for the single accumarray line with @mean or another way, I don’t care. Over the past three days I have been slopping together different nested loops to try to pin down the behavior I want and I’m sure there’s got to be a simple way to accomplish this.
I’m sure there’s a lot of other ways I could improve this code, but I just need it working. I’m not experienced and constantly bang my head against indexing problems (whether mixing up dimension, logical indexing oddities, etc.) and other beginner problems.
function [peakLoc, peakVal] = getExtrema(durThreshold, PEThreshold, gettingMax, PEAverage, timestep)
% Gets passed duration (# of consecutive timesteps above zero) and PE threshold (0).
% Returns the timestep and PE value for all of Maximum or of Minimum extrema.
if gettingMax == true
isPeak = PEAverage > PEThreshold;
else
isPeak = PEAverage < PEThreshold;
end
CC = bwconncomp(isPeak);
peakID = labelmatrix(CC);
peakLabel = unique(peakID);
peakSize = accumarray(peakID(:)+1,1);
peakSize(1) = 0; % set the # of <0 elements to 0
realPeakLabels = peakLabel(peakSize >= durThreshold);
isRealPeak = ismember(peakID,realPeakLabels);
% Now find the max in the real peaks (realPeakLabels?), accumarray will help
peakID(~isRealPeak) = 0;
if gettingMax == true
peakVal = accumarray(peakID(:)+1,PEAverage(:),[numel(peakSize) 1],@max,NaN);
else
peakVal = accumarray(peakID(:)+1,PEAverage(:),[numel(peakSize) 1],@min,NaN);
end
%% Get the right peakLoc, not the @mean
% @mean is approximation of the timestep where the real peak value occurs
peakLoc = accumarray(peakID(:)+1,timestep(:),[numel(peakSize) 1],@mean,NaN);
peakLoc = zeros(length(peakLabel),1);
j = 1;
for i = timestep
% Get the right index
if peakID(i) > j
j = peakID(i);
end
if ismember(j, realPeakLabels)
if gettingMax == true
if PEAverage(i) > peakVal(j)
peakLoc(j) = timestep(i);
end
else
if PEAverage(i) < peakVal(j)
peakLoc(j) = timestep(i);
end
end
end
end
peakVal(1) = NaN;
peakLoc(peakLoc == 0) = NaN;
end signal processing MATLAB Answers — New Questions
How can I make a power load which uses different power for a day?
I want to make a power load which consumes different power for a day. I have a data that shows how much power was consumed by a building for a day.
So I used Dynamic load block, but I failed to load the data to the block.
How can I make it?I want to make a power load which consumes different power for a day. I have a data that shows how much power was consumed by a building for a day.
So I used Dynamic load block, but I failed to load the data to the block.
How can I make it? I want to make a power load which consumes different power for a day. I have a data that shows how much power was consumed by a building for a day.
So I used Dynamic load block, but I failed to load the data to the block.
How can I make it? load, variable, variable load MATLAB Answers — New Questions
Please help as I am struggling to solve this homework problem.
An H-section copper conductor carries an overload current of 54000 A. Under steady state conditions, the surface temperature is 60°C.
The dimensions of the bar are given in Figure 1 overleaf, and you are asked to use a numerical method to produce a mesh plot of the temperature distribution and a graph of the temperature distribution along the line y = 0.
The electrical resistivity, ρ, of copper is 2 × 10-8 Ω m, and the thermal conductivity, κ, is 0.311 kW m-1 K-1.
The governing differential equation is ∂2T + ∂2T + g = 0 (1)
∂x2 ∂y2 κ where g is the (constant) generation rate of heat per unit volume:
g = i2ρ (2) and i is the current density.
Using an appropriate Numerical Technique:
Determine the temperature distribution to an accuracy of 4 significant figures
You are expected to hand in the following by the submission date:
Hints
The Gauss-Seidel technique used in Tutorial 9 can be adapted to the present problem by including the additional term g/κ in the finite difference equation. You can generate a mask array as in Tutorial 9 to specify the region of the array covered by the H cross- section.
Try calculating the solution over a square mesh for a range of step lengths h = 5 mm, 2.5 mm, 1.25 mm…
You can if you wish make use of the symmetry of the problem and model just one quarter of the conductor. However, the boundary conditions then become more difficult to apply.
The H section is of width 40mm, depth 30mm and cut outs on top and bottom of depth 10x width 20 mm
Any help would be most appreciated
Cheers
SamAn H-section copper conductor carries an overload current of 54000 A. Under steady state conditions, the surface temperature is 60°C.
The dimensions of the bar are given in Figure 1 overleaf, and you are asked to use a numerical method to produce a mesh plot of the temperature distribution and a graph of the temperature distribution along the line y = 0.
The electrical resistivity, ρ, of copper is 2 × 10-8 Ω m, and the thermal conductivity, κ, is 0.311 kW m-1 K-1.
The governing differential equation is ∂2T + ∂2T + g = 0 (1)
∂x2 ∂y2 κ where g is the (constant) generation rate of heat per unit volume:
g = i2ρ (2) and i is the current density.
Using an appropriate Numerical Technique:
Determine the temperature distribution to an accuracy of 4 significant figures
You are expected to hand in the following by the submission date:
Hints
The Gauss-Seidel technique used in Tutorial 9 can be adapted to the present problem by including the additional term g/κ in the finite difference equation. You can generate a mask array as in Tutorial 9 to specify the region of the array covered by the H cross- section.
Try calculating the solution over a square mesh for a range of step lengths h = 5 mm, 2.5 mm, 1.25 mm…
You can if you wish make use of the symmetry of the problem and model just one quarter of the conductor. However, the boundary conditions then become more difficult to apply.
The H section is of width 40mm, depth 30mm and cut outs on top and bottom of depth 10x width 20 mm
Any help would be most appreciated
Cheers
Sam An H-section copper conductor carries an overload current of 54000 A. Under steady state conditions, the surface temperature is 60°C.
The dimensions of the bar are given in Figure 1 overleaf, and you are asked to use a numerical method to produce a mesh plot of the temperature distribution and a graph of the temperature distribution along the line y = 0.
The electrical resistivity, ρ, of copper is 2 × 10-8 Ω m, and the thermal conductivity, κ, is 0.311 kW m-1 K-1.
The governing differential equation is ∂2T + ∂2T + g = 0 (1)
∂x2 ∂y2 κ where g is the (constant) generation rate of heat per unit volume:
g = i2ρ (2) and i is the current density.
Using an appropriate Numerical Technique:
Determine the temperature distribution to an accuracy of 4 significant figures
You are expected to hand in the following by the submission date:
Hints
The Gauss-Seidel technique used in Tutorial 9 can be adapted to the present problem by including the additional term g/κ in the finite difference equation. You can generate a mask array as in Tutorial 9 to specify the region of the array covered by the H cross- section.
Try calculating the solution over a square mesh for a range of step lengths h = 5 mm, 2.5 mm, 1.25 mm…
You can if you wish make use of the symmetry of the problem and model just one quarter of the conductor. However, the boundary conditions then become more difficult to apply.
The H section is of width 40mm, depth 30mm and cut outs on top and bottom of depth 10x width 20 mm
Any help would be most appreciated
Cheers
Sam differential equations, conductivity, homework, doit4me MATLAB Answers — New Questions
Syms suddenly doesnt work
Something what I have done many times and something that is in matlab helt suddently doesnt work? any idea how that is. Link to matlab help site: https://se.mathworks.com/help/symbolic/syms.html, look under "Create Vector of Symbolic Scalar Variables"
syms c [1 4]
And I get this error:
Warning: deprecated syntax used in sym constructor
> In sym (line 156)
In syms (line 56)
Error using assignin
Invalid variable name "[1 4]" in ASSIGNIN.
Error in syms (line 56)
assignin(‘caller’,varargin{i},sym(varargin{i}));Something what I have done many times and something that is in matlab helt suddently doesnt work? any idea how that is. Link to matlab help site: https://se.mathworks.com/help/symbolic/syms.html, look under "Create Vector of Symbolic Scalar Variables"
syms c [1 4]
And I get this error:
Warning: deprecated syntax used in sym constructor
> In sym (line 156)
In syms (line 56)
Error using assignin
Invalid variable name "[1 4]" in ASSIGNIN.
Error in syms (line 56)
assignin(‘caller’,varargin{i},sym(varargin{i})); Something what I have done many times and something that is in matlab helt suddently doesnt work? any idea how that is. Link to matlab help site: https://se.mathworks.com/help/symbolic/syms.html, look under "Create Vector of Symbolic Scalar Variables"
syms c [1 4]
And I get this error:
Warning: deprecated syntax used in sym constructor
> In sym (line 156)
In syms (line 56)
Error using assignin
Invalid variable name "[1 4]" in ASSIGNIN.
Error in syms (line 56)
assignin(‘caller’,varargin{i},sym(varargin{i})); symbolic MATLAB Answers — New Questions
Matlab live script – symbolic math looks terrible
1st picture is what my matlab live script symbolic math looks like now.
2nd picture is what i want it to look like and what it has looked like earlier.1st picture is what my matlab live script symbolic math looks like now.
2nd picture is what i want it to look like and what it has looked like earlier. 1st picture is what my matlab live script symbolic math looks like now.
2nd picture is what i want it to look like and what it has looked like earlier. matlab live script, live script, symbolic MATLAB Answers — New Questions
how to refactor variable/parameters names used in a whole simulink project
i have a big project (over 20 000 variables) in these variables some are used throughout the entire project in referenced models in certain blocks etc. the variables are mostly enums. i want to change ‘variableA’ to ‘variableB’ how would i do so?
the only thing i got is to change each and every one manualy by hand using a CTRL+F on the main model.
thanks for the help!i have a big project (over 20 000 variables) in these variables some are used throughout the entire project in referenced models in certain blocks etc. the variables are mostly enums. i want to change ‘variableA’ to ‘variableB’ how would i do so?
the only thing i got is to change each and every one manualy by hand using a CTRL+F on the main model.
thanks for the help! i have a big project (over 20 000 variables) in these variables some are used throughout the entire project in referenced models in certain blocks etc. the variables are mostly enums. i want to change ‘variableA’ to ‘variableB’ how would i do so?
the only thing i got is to change each and every one manualy by hand using a CTRL+F on the main model.
thanks for the help! refactor, rename, variable, enum, parameters MATLAB Answers — New Questions
How to load file with variables to each worker in parsim without TransferBaseWorkspaceVariables?
I would like to know how one can load a .mat file (filled with initialization variables) to each worker when using the parsim function (with the Parallel Computing Toolbox). This will be for a local machine with 8 workers. I am using parsim to run a large Monte Carlo analysis of a complex simulink model. This model requires a large set of initialization variables, which slows the total runtime considerably when I manually load the full set of them and use the "TransferBaseWorkspaceVariables" argument of parsim.
I have tried to use the "AttachedFiles" and "SetupFcn" arguments to load my initialization file (called "initVars.mat" and is located in my current work directory), as suggested in the following link: https://imathworks.com/matlab/matlab-how-to-avoid-transferring-all-the-workspace-variables-to-the-workers-when-using-parsim/
My code for the parsim implementation is as follows (with "inPar" being an array of Simulink Input objects):
parsim(inPar,’AttachedFiles’,{‘initVars.mat’},’SetupFcn’,evalin(‘base’,’load initVars.mat’));
I get the following error when trying to run the code:
Invalid expression. Check for missing multiplication operator, missing or unbalanced delimiters, or other syntax error. To construct matrices, use
brackets instead of parentheses.
I have tried different forms of the arguments in "evalin", with no success. I have also tried the same arguments with the "PreLoadFcn" modifier to the Input objects, also with no success.
It works when "evalin(‘base’,’load initVars.mat’)" is directly placed into the Simulink Model Properties’ Callbacks tab (into PreLoadFcn). However, I want to do things programmatically as far as possible.
I am using Matlab v2021b Update 3, with Simulink v10.4.
Any help would be appreciated.I would like to know how one can load a .mat file (filled with initialization variables) to each worker when using the parsim function (with the Parallel Computing Toolbox). This will be for a local machine with 8 workers. I am using parsim to run a large Monte Carlo analysis of a complex simulink model. This model requires a large set of initialization variables, which slows the total runtime considerably when I manually load the full set of them and use the "TransferBaseWorkspaceVariables" argument of parsim.
I have tried to use the "AttachedFiles" and "SetupFcn" arguments to load my initialization file (called "initVars.mat" and is located in my current work directory), as suggested in the following link: https://imathworks.com/matlab/matlab-how-to-avoid-transferring-all-the-workspace-variables-to-the-workers-when-using-parsim/
My code for the parsim implementation is as follows (with "inPar" being an array of Simulink Input objects):
parsim(inPar,’AttachedFiles’,{‘initVars.mat’},’SetupFcn’,evalin(‘base’,’load initVars.mat’));
I get the following error when trying to run the code:
Invalid expression. Check for missing multiplication operator, missing or unbalanced delimiters, or other syntax error. To construct matrices, use
brackets instead of parentheses.
I have tried different forms of the arguments in "evalin", with no success. I have also tried the same arguments with the "PreLoadFcn" modifier to the Input objects, also with no success.
It works when "evalin(‘base’,’load initVars.mat’)" is directly placed into the Simulink Model Properties’ Callbacks tab (into PreLoadFcn). However, I want to do things programmatically as far as possible.
I am using Matlab v2021b Update 3, with Simulink v10.4.
Any help would be appreciated. I would like to know how one can load a .mat file (filled with initialization variables) to each worker when using the parsim function (with the Parallel Computing Toolbox). This will be for a local machine with 8 workers. I am using parsim to run a large Monte Carlo analysis of a complex simulink model. This model requires a large set of initialization variables, which slows the total runtime considerably when I manually load the full set of them and use the "TransferBaseWorkspaceVariables" argument of parsim.
I have tried to use the "AttachedFiles" and "SetupFcn" arguments to load my initialization file (called "initVars.mat" and is located in my current work directory), as suggested in the following link: https://imathworks.com/matlab/matlab-how-to-avoid-transferring-all-the-workspace-variables-to-the-workers-when-using-parsim/
My code for the parsim implementation is as follows (with "inPar" being an array of Simulink Input objects):
parsim(inPar,’AttachedFiles’,{‘initVars.mat’},’SetupFcn’,evalin(‘base’,’load initVars.mat’));
I get the following error when trying to run the code:
Invalid expression. Check for missing multiplication operator, missing or unbalanced delimiters, or other syntax error. To construct matrices, use
brackets instead of parentheses.
I have tried different forms of the arguments in "evalin", with no success. I have also tried the same arguments with the "PreLoadFcn" modifier to the Input objects, also with no success.
It works when "evalin(‘base’,’load initVars.mat’)" is directly placed into the Simulink Model Properties’ Callbacks tab (into PreLoadFcn). However, I want to do things programmatically as far as possible.
I am using Matlab v2021b Update 3, with Simulink v10.4.
Any help would be appreciated. parsim, simulink, parallel computing toolbox, setupfcn, workspace, error MATLAB Answers — New Questions
Values changining after a satellite is initialized.
Hi,
Below is the code which I am using in order to create a satellite scenario. I have defined all the required parameters manually that are required to initialize a satellte, but I am not able to understand why are they getting changed after the satellite is initialized.
startTime = datetime(’27-Jun-2024 13:23:02′);
stopTime = startTime + seconds(60*100);
sampleTime = 10;
sc = satelliteScenario(startTime,stopTime,sampleTime);
mu = 3.986004418*1e14;
n = 15.06398680175205;
semiMajorAxis = nthroot(mu,3)/(((2*n*pi)/86400)^(2/3)) ;
trueAnomaly = 341.2089;
Eccentricity = 1.249e-04;
Inclination = 53.0534;
RightAscensionOfAscendingNode = 242.3386;
ArgumentOfPeriapsis = 94.5842;
sat = satellite(sc,semiMajorAxis,Eccentricity,Inclination,RightAscensionOfAscendingNode,ArgumentOfPeriapsis,trueAnomaly);
elements = orbitalElements(sat);
I would really appreciate if someone can help me figure out why are the values of RAAN and ArgumentOfPeriapsis getting changed after the satellite is initialized.
Thank youHi,
Below is the code which I am using in order to create a satellite scenario. I have defined all the required parameters manually that are required to initialize a satellte, but I am not able to understand why are they getting changed after the satellite is initialized.
startTime = datetime(’27-Jun-2024 13:23:02′);
stopTime = startTime + seconds(60*100);
sampleTime = 10;
sc = satelliteScenario(startTime,stopTime,sampleTime);
mu = 3.986004418*1e14;
n = 15.06398680175205;
semiMajorAxis = nthroot(mu,3)/(((2*n*pi)/86400)^(2/3)) ;
trueAnomaly = 341.2089;
Eccentricity = 1.249e-04;
Inclination = 53.0534;
RightAscensionOfAscendingNode = 242.3386;
ArgumentOfPeriapsis = 94.5842;
sat = satellite(sc,semiMajorAxis,Eccentricity,Inclination,RightAscensionOfAscendingNode,ArgumentOfPeriapsis,trueAnomaly);
elements = orbitalElements(sat);
I would really appreciate if someone can help me figure out why are the values of RAAN and ArgumentOfPeriapsis getting changed after the satellite is initialized.
Thank you Hi,
Below is the code which I am using in order to create a satellite scenario. I have defined all the required parameters manually that are required to initialize a satellte, but I am not able to understand why are they getting changed after the satellite is initialized.
startTime = datetime(’27-Jun-2024 13:23:02′);
stopTime = startTime + seconds(60*100);
sampleTime = 10;
sc = satelliteScenario(startTime,stopTime,sampleTime);
mu = 3.986004418*1e14;
n = 15.06398680175205;
semiMajorAxis = nthroot(mu,3)/(((2*n*pi)/86400)^(2/3)) ;
trueAnomaly = 341.2089;
Eccentricity = 1.249e-04;
Inclination = 53.0534;
RightAscensionOfAscendingNode = 242.3386;
ArgumentOfPeriapsis = 94.5842;
sat = satellite(sc,semiMajorAxis,Eccentricity,Inclination,RightAscensionOfAscendingNode,ArgumentOfPeriapsis,trueAnomaly);
elements = orbitalElements(sat);
I would really appreciate if someone can help me figure out why are the values of RAAN and ArgumentOfPeriapsis getting changed after the satellite is initialized.
Thank you communication, matlab MATLAB Answers — New Questions
How to correct 180-degree phase shift caused by negative feedback loop
I’m in the process of designing a cascaded PI controller by following a tutorial published by MathWork in 2022. By comparing the close-loop response and the open-loop response of the inner loop, i’m noticing a 180-degree phase shift. The tutorial states before working on the outer loop, this phase shift must be corrected. Can someone please explain how i can do that ? Thanks in advance.
Link to the tutorial:Cascade Digital PID Control Design for Power Electronic Converters – MATLAB & Simulink (mathworks.com)I’m in the process of designing a cascaded PI controller by following a tutorial published by MathWork in 2022. By comparing the close-loop response and the open-loop response of the inner loop, i’m noticing a 180-degree phase shift. The tutorial states before working on the outer loop, this phase shift must be corrected. Can someone please explain how i can do that ? Thanks in advance.
Link to the tutorial:Cascade Digital PID Control Design for Power Electronic Converters – MATLAB & Simulink (mathworks.com) I’m in the process of designing a cascaded PI controller by following a tutorial published by MathWork in 2022. By comparing the close-loop response and the open-loop response of the inner loop, i’m noticing a 180-degree phase shift. The tutorial states before working on the outer loop, this phase shift must be corrected. Can someone please explain how i can do that ? Thanks in advance.
Link to the tutorial:Cascade Digital PID Control Design for Power Electronic Converters – MATLAB & Simulink (mathworks.com) control, power_electronics_control MATLAB Answers — New Questions
Figure changes during export
Hello everyone. I have created a loop where my function would save a plot of a series of posterior tangents overlaying vertebrae of the cervical spine. The problem is, after my function runs (code displayed below) only 5 out of the 6 lines appear on the plot. If I run it in isolation in the command window, all 6 lines appear. I have attached the images, the plot pre export with all 6 lines (ran in command window) and post export with the incorrect number (run as a function). I have gone through a number of times and cannot figure out why one line disappears when exporting. Any ideas?
Thanks in advance.
PS I have commented out parts of the code that are not relevant for this question. I did not delete so you were not confused about the input/output variables of my function.
function [c1_c7_angle,c2_c7_angle,c2c3_tangent,c3c4_tangent,c4c5_tangent,c5c6_tangent,c6c7_tangent]=rotation_angles(c1x,c1y,c2x,c2y,c3x,c3y,c4x,c4y,c5x,c5y,c6x,c6y,c7x,c7y,new_filename,i2)
%define posterior corners.
c2post=[c2x(1) c2y(1); c2x(4) c2y(4)];
c3post=[c3x(1) c3y(1); c3x(4) c3y(4)];
c4post=[c4x(1) c4y(1); c4x(4) c4y(4)];
c5post=[c5x(1) c5y(1); c5x(4) c5y(4)];
c6post=[c6x(1) c6y(1); c6x(4) c6y(4)];
c7post=[c7x(1) c7y(1); c7x(4) c7y(4)];
%c2_angle=rad2deg(atan((c2post(2,2)-c2post(1,2))/(c2post(2,1)-c2post(1,1))));
%c3_angle=rad2deg(atan((c3post(2,2)-c3post(1,2))/(c3post(2,1)-c3post(1,1))));
%c4_angle=rad2deg(atan((c4post(2,2)-c4post(1,2))/(c4post(2,1)-c4post(1,1))));
%c5_angle=rad2deg(atan((c5post(2,2)-c5post(1,2))/(c5post(2,1)-c5post(1,1))));
%c6_angle=rad2deg(atan((c6post(2,2)-c6post(1,2))/(c6post(2,1)-c6post(1,1))));
%c7_angle=rad2deg(atan((c7post(2,2)-c7post(1,2))/(c7post(2,1)-c7post(1,1))));
%c2c3_tangent=c2_angle-c3_angle;
%c3c4_tangent=c3_angle-c4_angle;
%c4c5_tangent=c4_angle-c5_angle;
%c5c6_tangent=c5_angle-c6_angle;
%c6c7_tangent=c6_angle-c7_angle;
%calculate c21-c7 angle by defining angle of inferior vertebral points.
%c1_angle=rad2deg(atan((c1y(1)-c1y(2))/(c1x(2)-c1x(1))));
%c2_inf_ang=rad2deg(atan((c2y(3)-c2y(4))/(c2x(3)-c2x(4))));
%c7_inf_ang=rad2deg(atan((c7y(3)-c7y(4))/(c7x(3)-c7x(4))));
%c1_c7_angle=c7_inf_ang-c1_angle;
%c2_c7_angle=c7_inf_ang-c2_inf_ang;
vertebra_matrix=[c2post;c3post;c4post;c5post;c6post;c7post];
post_x=[c2x(1) c2x(4) c3x(1) c3x(4) c4x(1) c4x(4) c5x(1) c5x(4) c6x(1) c6x(4) c7x(1) c7x(4)];
post_y=[c2y(1) c2y(4) c3y(1) c3y(4) c4y(1) c4y(4) c5y(1) c5y(4) c6y(1) c6y(4) c7y(1) c7y(4)];
theta=zeros([1 6]);
x_diff=zeros([1 6]);
y_diff=zeros([1 6]);
V=zeros([6 2]);
factor_distance=2;
imshow(i2,’InitialMagnification’,100);
hold on;
for h=1:6
f=h*2;
d=f-1;
x_diff(h)=post_x(d)-post_x(f);
y_diff(h)=post_y(f)-post_y(d);
theta(h)=rad2deg(atan(y_diff/x_diff));
V(h,:)=vertebra_matrix(d,:)-vertebra_matrix(f,:);
pext(h,:)=vertebra_matrix(h,:)+V(h,:)*factor_distance;
ax=gca;
output_filename=sprintf(‘%s_rotation.tif’,new_filename);
exportgraphics(ax,output_filename);
plot([post_x(f),pext(h,1)],[post_y(f),pext(h,2)],’r-‘)
end
endHello everyone. I have created a loop where my function would save a plot of a series of posterior tangents overlaying vertebrae of the cervical spine. The problem is, after my function runs (code displayed below) only 5 out of the 6 lines appear on the plot. If I run it in isolation in the command window, all 6 lines appear. I have attached the images, the plot pre export with all 6 lines (ran in command window) and post export with the incorrect number (run as a function). I have gone through a number of times and cannot figure out why one line disappears when exporting. Any ideas?
Thanks in advance.
PS I have commented out parts of the code that are not relevant for this question. I did not delete so you were not confused about the input/output variables of my function.
function [c1_c7_angle,c2_c7_angle,c2c3_tangent,c3c4_tangent,c4c5_tangent,c5c6_tangent,c6c7_tangent]=rotation_angles(c1x,c1y,c2x,c2y,c3x,c3y,c4x,c4y,c5x,c5y,c6x,c6y,c7x,c7y,new_filename,i2)
%define posterior corners.
c2post=[c2x(1) c2y(1); c2x(4) c2y(4)];
c3post=[c3x(1) c3y(1); c3x(4) c3y(4)];
c4post=[c4x(1) c4y(1); c4x(4) c4y(4)];
c5post=[c5x(1) c5y(1); c5x(4) c5y(4)];
c6post=[c6x(1) c6y(1); c6x(4) c6y(4)];
c7post=[c7x(1) c7y(1); c7x(4) c7y(4)];
%c2_angle=rad2deg(atan((c2post(2,2)-c2post(1,2))/(c2post(2,1)-c2post(1,1))));
%c3_angle=rad2deg(atan((c3post(2,2)-c3post(1,2))/(c3post(2,1)-c3post(1,1))));
%c4_angle=rad2deg(atan((c4post(2,2)-c4post(1,2))/(c4post(2,1)-c4post(1,1))));
%c5_angle=rad2deg(atan((c5post(2,2)-c5post(1,2))/(c5post(2,1)-c5post(1,1))));
%c6_angle=rad2deg(atan((c6post(2,2)-c6post(1,2))/(c6post(2,1)-c6post(1,1))));
%c7_angle=rad2deg(atan((c7post(2,2)-c7post(1,2))/(c7post(2,1)-c7post(1,1))));
%c2c3_tangent=c2_angle-c3_angle;
%c3c4_tangent=c3_angle-c4_angle;
%c4c5_tangent=c4_angle-c5_angle;
%c5c6_tangent=c5_angle-c6_angle;
%c6c7_tangent=c6_angle-c7_angle;
%calculate c21-c7 angle by defining angle of inferior vertebral points.
%c1_angle=rad2deg(atan((c1y(1)-c1y(2))/(c1x(2)-c1x(1))));
%c2_inf_ang=rad2deg(atan((c2y(3)-c2y(4))/(c2x(3)-c2x(4))));
%c7_inf_ang=rad2deg(atan((c7y(3)-c7y(4))/(c7x(3)-c7x(4))));
%c1_c7_angle=c7_inf_ang-c1_angle;
%c2_c7_angle=c7_inf_ang-c2_inf_ang;
vertebra_matrix=[c2post;c3post;c4post;c5post;c6post;c7post];
post_x=[c2x(1) c2x(4) c3x(1) c3x(4) c4x(1) c4x(4) c5x(1) c5x(4) c6x(1) c6x(4) c7x(1) c7x(4)];
post_y=[c2y(1) c2y(4) c3y(1) c3y(4) c4y(1) c4y(4) c5y(1) c5y(4) c6y(1) c6y(4) c7y(1) c7y(4)];
theta=zeros([1 6]);
x_diff=zeros([1 6]);
y_diff=zeros([1 6]);
V=zeros([6 2]);
factor_distance=2;
imshow(i2,’InitialMagnification’,100);
hold on;
for h=1:6
f=h*2;
d=f-1;
x_diff(h)=post_x(d)-post_x(f);
y_diff(h)=post_y(f)-post_y(d);
theta(h)=rad2deg(atan(y_diff/x_diff));
V(h,:)=vertebra_matrix(d,:)-vertebra_matrix(f,:);
pext(h,:)=vertebra_matrix(h,:)+V(h,:)*factor_distance;
ax=gca;
output_filename=sprintf(‘%s_rotation.tif’,new_filename);
exportgraphics(ax,output_filename);
plot([post_x(f),pext(h,1)],[post_y(f),pext(h,2)],’r-‘)
end
end Hello everyone. I have created a loop where my function would save a plot of a series of posterior tangents overlaying vertebrae of the cervical spine. The problem is, after my function runs (code displayed below) only 5 out of the 6 lines appear on the plot. If I run it in isolation in the command window, all 6 lines appear. I have attached the images, the plot pre export with all 6 lines (ran in command window) and post export with the incorrect number (run as a function). I have gone through a number of times and cannot figure out why one line disappears when exporting. Any ideas?
Thanks in advance.
PS I have commented out parts of the code that are not relevant for this question. I did not delete so you were not confused about the input/output variables of my function.
function [c1_c7_angle,c2_c7_angle,c2c3_tangent,c3c4_tangent,c4c5_tangent,c5c6_tangent,c6c7_tangent]=rotation_angles(c1x,c1y,c2x,c2y,c3x,c3y,c4x,c4y,c5x,c5y,c6x,c6y,c7x,c7y,new_filename,i2)
%define posterior corners.
c2post=[c2x(1) c2y(1); c2x(4) c2y(4)];
c3post=[c3x(1) c3y(1); c3x(4) c3y(4)];
c4post=[c4x(1) c4y(1); c4x(4) c4y(4)];
c5post=[c5x(1) c5y(1); c5x(4) c5y(4)];
c6post=[c6x(1) c6y(1); c6x(4) c6y(4)];
c7post=[c7x(1) c7y(1); c7x(4) c7y(4)];
%c2_angle=rad2deg(atan((c2post(2,2)-c2post(1,2))/(c2post(2,1)-c2post(1,1))));
%c3_angle=rad2deg(atan((c3post(2,2)-c3post(1,2))/(c3post(2,1)-c3post(1,1))));
%c4_angle=rad2deg(atan((c4post(2,2)-c4post(1,2))/(c4post(2,1)-c4post(1,1))));
%c5_angle=rad2deg(atan((c5post(2,2)-c5post(1,2))/(c5post(2,1)-c5post(1,1))));
%c6_angle=rad2deg(atan((c6post(2,2)-c6post(1,2))/(c6post(2,1)-c6post(1,1))));
%c7_angle=rad2deg(atan((c7post(2,2)-c7post(1,2))/(c7post(2,1)-c7post(1,1))));
%c2c3_tangent=c2_angle-c3_angle;
%c3c4_tangent=c3_angle-c4_angle;
%c4c5_tangent=c4_angle-c5_angle;
%c5c6_tangent=c5_angle-c6_angle;
%c6c7_tangent=c6_angle-c7_angle;
%calculate c21-c7 angle by defining angle of inferior vertebral points.
%c1_angle=rad2deg(atan((c1y(1)-c1y(2))/(c1x(2)-c1x(1))));
%c2_inf_ang=rad2deg(atan((c2y(3)-c2y(4))/(c2x(3)-c2x(4))));
%c7_inf_ang=rad2deg(atan((c7y(3)-c7y(4))/(c7x(3)-c7x(4))));
%c1_c7_angle=c7_inf_ang-c1_angle;
%c2_c7_angle=c7_inf_ang-c2_inf_ang;
vertebra_matrix=[c2post;c3post;c4post;c5post;c6post;c7post];
post_x=[c2x(1) c2x(4) c3x(1) c3x(4) c4x(1) c4x(4) c5x(1) c5x(4) c6x(1) c6x(4) c7x(1) c7x(4)];
post_y=[c2y(1) c2y(4) c3y(1) c3y(4) c4y(1) c4y(4) c5y(1) c5y(4) c6y(1) c6y(4) c7y(1) c7y(4)];
theta=zeros([1 6]);
x_diff=zeros([1 6]);
y_diff=zeros([1 6]);
V=zeros([6 2]);
factor_distance=2;
imshow(i2,’InitialMagnification’,100);
hold on;
for h=1:6
f=h*2;
d=f-1;
x_diff(h)=post_x(d)-post_x(f);
y_diff(h)=post_y(f)-post_y(d);
theta(h)=rad2deg(atan(y_diff/x_diff));
V(h,:)=vertebra_matrix(d,:)-vertebra_matrix(f,:);
pext(h,:)=vertebra_matrix(h,:)+V(h,:)*factor_distance;
ax=gca;
output_filename=sprintf(‘%s_rotation.tif’,new_filename);
exportgraphics(ax,output_filename);
plot([post_x(f),pext(h,1)],[post_y(f),pext(h,2)],’r-‘)
end
end figure, plot MATLAB Answers — New Questions
How to convert datetime into a number?
I have a table whose first column is a timestamp in the format 08-Jan-2016 05:40:00. How do I convert it into numbers?
Wanted output: 20160108054000.
I know the function yyyymmdd(X) is useful but I also need the time to be added.
Thanks!I have a table whose first column is a timestamp in the format 08-Jan-2016 05:40:00. How do I convert it into numbers?
Wanted output: 20160108054000.
I know the function yyyymmdd(X) is useful but I also need the time to be added.
Thanks! I have a table whose first column is a timestamp in the format 08-Jan-2016 05:40:00. How do I convert it into numbers?
Wanted output: 20160108054000.
I know the function yyyymmdd(X) is useful but I also need the time to be added.
Thanks! datetime, string, char, date, time, convert MATLAB Answers — New Questions
How to correctly calculate three-phase voltage at the PCC parallel point ?
I simulated STATCOM model and found that the calculated voltage at PCC point is not correct with the discrete solver used, how to get the correct voltage? Here is the model file I built.Thanks.I simulated STATCOM model and found that the calculated voltage at PCC point is not correct with the discrete solver used, how to get the correct voltage? Here is the model file I built.Thanks. I simulated STATCOM model and found that the calculated voltage at PCC point is not correct with the discrete solver used, how to get the correct voltage? Here is the model file I built.Thanks. three-phase inverter, static reactive power compensator, power quality MATLAB Answers — New Questions
Python virtual environments with MATLAB
How can I use virtual environments with MATLAB’s Python Interface?How can I use virtual environments with MATLAB’s Python Interface? How can I use virtual environments with MATLAB’s Python Interface? MATLAB Answers — New Questions
How to save a MATLAB Simulink based simulaton with scopes data intact for future viewing?
I have a simulation on MATLAB Simulink. I run the simulation and I can view the results on scopes. I can save the results from scopes as MATLAB figures, etc. I can also save the workspace (full or partial).
What I want to do is that when I close the simulation, and open it again, it should be at the point where I closed it. In other words, I want to run a simulation and save it in such a way whenever I need it, I just need to open that file without the need to run it again. In this way, I do not have to save all the results of the scopes one by one. This will speed up my work. It will also help me to save my hard disk space. Moreover, I will not have to spend time to decide which result is important and which is not. I can just open a pre-run simulation and view my required results.I have a simulation on MATLAB Simulink. I run the simulation and I can view the results on scopes. I can save the results from scopes as MATLAB figures, etc. I can also save the workspace (full or partial).
What I want to do is that when I close the simulation, and open it again, it should be at the point where I closed it. In other words, I want to run a simulation and save it in such a way whenever I need it, I just need to open that file without the need to run it again. In this way, I do not have to save all the results of the scopes one by one. This will speed up my work. It will also help me to save my hard disk space. Moreover, I will not have to spend time to decide which result is important and which is not. I can just open a pre-run simulation and view my required results. I have a simulation on MATLAB Simulink. I run the simulation and I can view the results on scopes. I can save the results from scopes as MATLAB figures, etc. I can also save the workspace (full or partial).
What I want to do is that when I close the simulation, and open it again, it should be at the point where I closed it. In other words, I want to run a simulation and save it in such a way whenever I need it, I just need to open that file without the need to run it again. In this way, I do not have to save all the results of the scopes one by one. This will speed up my work. It will also help me to save my hard disk space. Moreover, I will not have to spend time to decide which result is important and which is not. I can just open a pre-run simulation and view my required results. saving a simulation MATLAB Answers — New Questions
I always got error on modelout after I upgraded to R2023.
I have a problem on modelout when I get my parafac result.
I don’t know what I should do on those error..I have a problem on modelout when I get my parafac result.
I don’t know what I should do on those error.. I have a problem on modelout when I get my parafac result.
I don’t know what I should do on those error.. parafac, modelout, excel, export MATLAB Answers — New Questions