Tag Archives: matlab
Good evening, we have a point cloud and have applied an first rotation to align the point cloud along the y-axis. Now we have a problem with a second rotation
clear all
close all
clc
%%
movingReg=pcread(‘v65_ts40_repeatibility_four9.ply’);
figure, pcshow(movingReg), view([0 0 ]), axis on, xlabel(‘x [mm]’), ylabel(‘y [mm]’), zlabel(‘z [mm]’)
%% roi dove ci sono i quattro fori
roi = [360 540 -155 -130 40 115]; % DA CAD
indices = findPointsInROI(movingReg,roi);
ptCloudB = select(movingReg,indices);
figure, pcshow(ptCloudB)
%% punto medio della nuvola di punti
centro=[mean(ptCloudB.Location(:,1)) mean(ptCloudB.Location(:,2)) mean(ptCloudB.Location(:,3))];
%% codice dato da Paolo per l’allineamento della nuvola
XYZ=[ptCloudB.Location(:,1) ptCloudB.Location(:,2) ptCloudB.Location(:,3)];
xyz0=mean(XYZ,1);
A=XYZ-xyz0;
[~,~,V]=svd(A,0);
a=cross(V(:,3),[0;0;1]);
T=makehgtform(‘axisrotate’, a, -atan2(norm(a),V(3,3)));
R=T(1:3,1:3);
A_rot = A*R;
% A_rot_pt=pointCloud(A_rot);
A_rot_p(:,1)=A_rot(:,1);
A_rot_p(:,3)=A_rot(:,2);
A_rot_p(:,2)=A_rot(:,3);
A_rot_p=pointCloud(A_rot_p);
figure, pcshow(A_rot_p),axis on, xlabel(‘x [mm]’), ylabel(‘y [mm]’), zlabel(‘z [mm]’)
%% applico una seconda svd
XYZ2=[A_rot_p.Location(:,1) A_rot_p.Location(:,2) A_rot_p.Location(:,3)];
xyz0_2=mean(XYZ2,1);
A=XYZ2-xyz0_2;
[~,~,V]=svd(A,0);
a=cross(V(:,1),[0;1;0]);%cross(V(:,2),[0;1;0]);
% T=makehgtform(‘zrotate’, -atan2(norm(a),V(2,1)));
if (V(1,2))>0
T=makehgtform(‘axisrotate’, [0 1 0], -atan2(norm(a),V(1,2)));
else
T=makehgtform(‘axisrotate’, [0 1 0], -atan2(norm(a),-V(1,2)));
endclear all
close all
clc
%%
movingReg=pcread(‘v65_ts40_repeatibility_four9.ply’);
figure, pcshow(movingReg), view([0 0 ]), axis on, xlabel(‘x [mm]’), ylabel(‘y [mm]’), zlabel(‘z [mm]’)
%% roi dove ci sono i quattro fori
roi = [360 540 -155 -130 40 115]; % DA CAD
indices = findPointsInROI(movingReg,roi);
ptCloudB = select(movingReg,indices);
figure, pcshow(ptCloudB)
%% punto medio della nuvola di punti
centro=[mean(ptCloudB.Location(:,1)) mean(ptCloudB.Location(:,2)) mean(ptCloudB.Location(:,3))];
%% codice dato da Paolo per l’allineamento della nuvola
XYZ=[ptCloudB.Location(:,1) ptCloudB.Location(:,2) ptCloudB.Location(:,3)];
xyz0=mean(XYZ,1);
A=XYZ-xyz0;
[~,~,V]=svd(A,0);
a=cross(V(:,3),[0;0;1]);
T=makehgtform(‘axisrotate’, a, -atan2(norm(a),V(3,3)));
R=T(1:3,1:3);
A_rot = A*R;
% A_rot_pt=pointCloud(A_rot);
A_rot_p(:,1)=A_rot(:,1);
A_rot_p(:,3)=A_rot(:,2);
A_rot_p(:,2)=A_rot(:,3);
A_rot_p=pointCloud(A_rot_p);
figure, pcshow(A_rot_p),axis on, xlabel(‘x [mm]’), ylabel(‘y [mm]’), zlabel(‘z [mm]’)
%% applico una seconda svd
XYZ2=[A_rot_p.Location(:,1) A_rot_p.Location(:,2) A_rot_p.Location(:,3)];
xyz0_2=mean(XYZ2,1);
A=XYZ2-xyz0_2;
[~,~,V]=svd(A,0);
a=cross(V(:,1),[0;1;0]);%cross(V(:,2),[0;1;0]);
% T=makehgtform(‘zrotate’, -atan2(norm(a),V(2,1)));
if (V(1,2))>0
T=makehgtform(‘axisrotate’, [0 1 0], -atan2(norm(a),V(1,2)));
else
T=makehgtform(‘axisrotate’, [0 1 0], -atan2(norm(a),-V(1,2)));
end clear all
close all
clc
%%
movingReg=pcread(‘v65_ts40_repeatibility_four9.ply’);
figure, pcshow(movingReg), view([0 0 ]), axis on, xlabel(‘x [mm]’), ylabel(‘y [mm]’), zlabel(‘z [mm]’)
%% roi dove ci sono i quattro fori
roi = [360 540 -155 -130 40 115]; % DA CAD
indices = findPointsInROI(movingReg,roi);
ptCloudB = select(movingReg,indices);
figure, pcshow(ptCloudB)
%% punto medio della nuvola di punti
centro=[mean(ptCloudB.Location(:,1)) mean(ptCloudB.Location(:,2)) mean(ptCloudB.Location(:,3))];
%% codice dato da Paolo per l’allineamento della nuvola
XYZ=[ptCloudB.Location(:,1) ptCloudB.Location(:,2) ptCloudB.Location(:,3)];
xyz0=mean(XYZ,1);
A=XYZ-xyz0;
[~,~,V]=svd(A,0);
a=cross(V(:,3),[0;0;1]);
T=makehgtform(‘axisrotate’, a, -atan2(norm(a),V(3,3)));
R=T(1:3,1:3);
A_rot = A*R;
% A_rot_pt=pointCloud(A_rot);
A_rot_p(:,1)=A_rot(:,1);
A_rot_p(:,3)=A_rot(:,2);
A_rot_p(:,2)=A_rot(:,3);
A_rot_p=pointCloud(A_rot_p);
figure, pcshow(A_rot_p),axis on, xlabel(‘x [mm]’), ylabel(‘y [mm]’), zlabel(‘z [mm]’)
%% applico una seconda svd
XYZ2=[A_rot_p.Location(:,1) A_rot_p.Location(:,2) A_rot_p.Location(:,3)];
xyz0_2=mean(XYZ2,1);
A=XYZ2-xyz0_2;
[~,~,V]=svd(A,0);
a=cross(V(:,1),[0;1;0]);%cross(V(:,2),[0;1;0]);
% T=makehgtform(‘zrotate’, -atan2(norm(a),V(2,1)));
if (V(1,2))>0
T=makehgtform(‘axisrotate’, [0 1 0], -atan2(norm(a),V(1,2)));
else
T=makehgtform(‘axisrotate’, [0 1 0], -atan2(norm(a),-V(1,2)));
end point cloud, data rotation MATLAB Answers — New Questions
Reading ADC data from MSP430 to Matlab via serial port
My situation is
1. external ADC samples from one channel and transmit to Serial port Via Uart and then switches over to second channel to do same and then third.
2. I manage to view data in Hterm and it looked quite fine.
3. I want to plot it live in matlab- I know there are ways to do it but can someone here explain me a basic step by step to achieve my objective?
I have basic idea of what i should be doing
setup serial communication.
create array to store uart values
calculate voltage values
plot live values
It would be nice if someone points out me for where to look for point 2 and 4 specifically.My situation is
1. external ADC samples from one channel and transmit to Serial port Via Uart and then switches over to second channel to do same and then third.
2. I manage to view data in Hterm and it looked quite fine.
3. I want to plot it live in matlab- I know there are ways to do it but can someone here explain me a basic step by step to achieve my objective?
I have basic idea of what i should be doing
setup serial communication.
create array to store uart values
calculate voltage values
plot live values
It would be nice if someone points out me for where to look for point 2 and 4 specifically. My situation is
1. external ADC samples from one channel and transmit to Serial port Via Uart and then switches over to second channel to do same and then third.
2. I manage to view data in Hterm and it looked quite fine.
3. I want to plot it live in matlab- I know there are ways to do it but can someone here explain me a basic step by step to achieve my objective?
I have basic idea of what i should be doing
setup serial communication.
create array to store uart values
calculate voltage values
plot live values
It would be nice if someone points out me for where to look for point 2 and 4 specifically. msp430, adc, uart, serial MATLAB Answers — New Questions
Why am I unable to change the user on the Online Training Suite License?
Why am I unable to change the user on the Online Training Suite License?Why am I unable to change the user on the Online Training Suite License? Why am I unable to change the user on the Online Training Suite License? MATLAB Answers — New Questions
Shiftet values of omega in bode plot as result from generating idfrd() and tfest()
Hello,
i have a problem at the calculation / estimation of a transfer function when using frequency-domain data.
My task is to get the continious transfer function for further simulation from measured magnitude and phase response by an impedance analyser.
The quality of the estimated curve is ok, but the problem is that the curve is shifted in omega and i cannot observe the problem.
The frequency limits of the measured data are 20 Hz to 5000 Hz with the units (freq. [Hz], magn [-], phase [°]).
Figure 1 and Figrue 2 shows the magnitude and phase of the measured data.
In Figure 3 shows the bode plot with idfrd() / frd() and the estimated TF.
Here the values are shiftet.
What ist the problem in this case?
format short g
clear
matt = readmatrix(‘data.CSV’);
fre = matt(1:300,1);
frerad = fre.*(pi/180);
abso = matt(1:300,2);
absdb = 20*log10(abso);
phdeg = matt(1:300,3);
phrad = phdeg.*(pi/180);
% options = bodeoptions;
% options.FreqUnits = ‘Hz’;
figure(1)
semilogx(fre,absdb)
legend()
ylabel(‘magn. [dB]’)
xlabel(‘freq. [Hz]’)
grid()
figure(2)
semilogx(fre,phdeg)
ylabel(‘magn. [dB]’)
xlabel(‘freq. [Hz]’)
legend()
grid()
complexVector = abso.* exp(1j*phrad);
vect_mess = idfrd(complexVector,frerad,0);
% vect_mess = frd(complexVector,frerad);
tf_estimated = tfest(vect_mess,3)
figure(3)
bode(vect_mess,tf_estimated )
legend()
grid()Hello,
i have a problem at the calculation / estimation of a transfer function when using frequency-domain data.
My task is to get the continious transfer function for further simulation from measured magnitude and phase response by an impedance analyser.
The quality of the estimated curve is ok, but the problem is that the curve is shifted in omega and i cannot observe the problem.
The frequency limits of the measured data are 20 Hz to 5000 Hz with the units (freq. [Hz], magn [-], phase [°]).
Figure 1 and Figrue 2 shows the magnitude and phase of the measured data.
In Figure 3 shows the bode plot with idfrd() / frd() and the estimated TF.
Here the values are shiftet.
What ist the problem in this case?
format short g
clear
matt = readmatrix(‘data.CSV’);
fre = matt(1:300,1);
frerad = fre.*(pi/180);
abso = matt(1:300,2);
absdb = 20*log10(abso);
phdeg = matt(1:300,3);
phrad = phdeg.*(pi/180);
% options = bodeoptions;
% options.FreqUnits = ‘Hz’;
figure(1)
semilogx(fre,absdb)
legend()
ylabel(‘magn. [dB]’)
xlabel(‘freq. [Hz]’)
grid()
figure(2)
semilogx(fre,phdeg)
ylabel(‘magn. [dB]’)
xlabel(‘freq. [Hz]’)
legend()
grid()
complexVector = abso.* exp(1j*phrad);
vect_mess = idfrd(complexVector,frerad,0);
% vect_mess = frd(complexVector,frerad);
tf_estimated = tfest(vect_mess,3)
figure(3)
bode(vect_mess,tf_estimated )
legend()
grid() Hello,
i have a problem at the calculation / estimation of a transfer function when using frequency-domain data.
My task is to get the continious transfer function for further simulation from measured magnitude and phase response by an impedance analyser.
The quality of the estimated curve is ok, but the problem is that the curve is shifted in omega and i cannot observe the problem.
The frequency limits of the measured data are 20 Hz to 5000 Hz with the units (freq. [Hz], magn [-], phase [°]).
Figure 1 and Figrue 2 shows the magnitude and phase of the measured data.
In Figure 3 shows the bode plot with idfrd() / frd() and the estimated TF.
Here the values are shiftet.
What ist the problem in this case?
format short g
clear
matt = readmatrix(‘data.CSV’);
fre = matt(1:300,1);
frerad = fre.*(pi/180);
abso = matt(1:300,2);
absdb = 20*log10(abso);
phdeg = matt(1:300,3);
phrad = phdeg.*(pi/180);
% options = bodeoptions;
% options.FreqUnits = ‘Hz’;
figure(1)
semilogx(fre,absdb)
legend()
ylabel(‘magn. [dB]’)
xlabel(‘freq. [Hz]’)
grid()
figure(2)
semilogx(fre,phdeg)
ylabel(‘magn. [dB]’)
xlabel(‘freq. [Hz]’)
legend()
grid()
complexVector = abso.* exp(1j*phrad);
vect_mess = idfrd(complexVector,frerad,0);
% vect_mess = frd(complexVector,frerad);
tf_estimated = tfest(vect_mess,3)
figure(3)
bode(vect_mess,tf_estimated )
legend()
grid() transfer function, estimation tfest MATLAB Answers — New Questions
After completing Matlab onramp my progress bar keeps changing back to 87% with some modules saying they aren’t completed after recieving a certificate with 100% completion.
I have completed the Matlab onramp and recieved a certificate saying 100% complettion, despite issues with the website proccessing this it finally went through. After returning to the MathWorks site to link my certificate to linkedin my progress has gone back down to 87% saying that some modules are incomplete- with the effect of reducing the progress score on my certificate down to 87%.I have completed the Matlab onramp and recieved a certificate saying 100% complettion, despite issues with the website proccessing this it finally went through. After returning to the MathWorks site to link my certificate to linkedin my progress has gone back down to 87% saying that some modules are incomplete- with the effect of reducing the progress score on my certificate down to 87%. I have completed the Matlab onramp and recieved a certificate saying 100% complettion, despite issues with the website proccessing this it finally went through. After returning to the MathWorks site to link my certificate to linkedin my progress has gone back down to 87% saying that some modules are incomplete- with the effect of reducing the progress score on my certificate down to 87%. onramp MATLAB Answers — New Questions
Leave-out-one cross validation during neural network training
Hello there I am trying to train a ML model with leave-out-one trial cross validation. Right now I have input data stored in the 1×10 cell array: "XTrain" with each cell containing the prediction inputs for all 10 trials and another 1×10 cell array: "YTrain" that contains the correposding continous variable we are trying to predict/output.
net = connectLayers(net,outputName,"fc");
% Specify training options
options = trainingOptions(‘adam’, …
‘MaxEpochs’, 60, …
‘MiniBatchSize’, 1, …
‘SequenceLength’, ‘longest’, …
‘InputDataFormats’, ‘CTB’, …
‘Plots’, ‘training-progress’, …
‘Metrics’, ‘rmse’, …
‘Verbose’, 0 …
‘Validation);
% Train the network
net = trainnet(XTrain,YTrain,net,"mse",options)
I have built my model’s network architecture stored in "net", but I am unsure of how to incorporte "leave out one trial" validation during training and then test my model’s performance. I want the model to pull out one trial at a time and then train the model and continue to do this for all 10 trials so that I end up with one final network trained and validated on all the trials. But I also want to have data to test the model’s performance? Do I need to create a loop for this? or is there a way I can specify this in the training options? Any help would be greatly appreciated!Hello there I am trying to train a ML model with leave-out-one trial cross validation. Right now I have input data stored in the 1×10 cell array: "XTrain" with each cell containing the prediction inputs for all 10 trials and another 1×10 cell array: "YTrain" that contains the correposding continous variable we are trying to predict/output.
net = connectLayers(net,outputName,"fc");
% Specify training options
options = trainingOptions(‘adam’, …
‘MaxEpochs’, 60, …
‘MiniBatchSize’, 1, …
‘SequenceLength’, ‘longest’, …
‘InputDataFormats’, ‘CTB’, …
‘Plots’, ‘training-progress’, …
‘Metrics’, ‘rmse’, …
‘Verbose’, 0 …
‘Validation);
% Train the network
net = trainnet(XTrain,YTrain,net,"mse",options)
I have built my model’s network architecture stored in "net", but I am unsure of how to incorporte "leave out one trial" validation during training and then test my model’s performance. I want the model to pull out one trial at a time and then train the model and continue to do this for all 10 trials so that I end up with one final network trained and validated on all the trials. But I also want to have data to test the model’s performance? Do I need to create a loop for this? or is there a way I can specify this in the training options? Any help would be greatly appreciated! Hello there I am trying to train a ML model with leave-out-one trial cross validation. Right now I have input data stored in the 1×10 cell array: "XTrain" with each cell containing the prediction inputs for all 10 trials and another 1×10 cell array: "YTrain" that contains the correposding continous variable we are trying to predict/output.
net = connectLayers(net,outputName,"fc");
% Specify training options
options = trainingOptions(‘adam’, …
‘MaxEpochs’, 60, …
‘MiniBatchSize’, 1, …
‘SequenceLength’, ‘longest’, …
‘InputDataFormats’, ‘CTB’, …
‘Plots’, ‘training-progress’, …
‘Metrics’, ‘rmse’, …
‘Verbose’, 0 …
‘Validation);
% Train the network
net = trainnet(XTrain,YTrain,net,"mse",options)
I have built my model’s network architecture stored in "net", but I am unsure of how to incorporte "leave out one trial" validation during training and then test my model’s performance. I want the model to pull out one trial at a time and then train the model and continue to do this for all 10 trials so that I end up with one final network trained and validated on all the trials. But I also want to have data to test the model’s performance? Do I need to create a loop for this? or is there a way I can specify this in the training options? Any help would be greatly appreciated! machine learning, validation, neural network, trainnet MATLAB Answers — New Questions
Incorrect Data Interpretation in UDP Reception with Simulink
On an ESP32, I am sending distance data via UDP to MATLAB. There are multiple distances involved, so both the receiver number (from 81 to 84) and the respective distance are transmitted. I can also receive and analyze the data using the following program:
% Set up the UDP receiver
udpReceiver = udpport("LocalPort", 4141);
% Define a function to parse the received UDP packet
% Main loop to continuously receive and display distances
while true
% Check if a packet is available
if udpReceiver.NumBytesAvailable > 0
% Read the packet
packet = read(udpReceiver, udpReceiver.NumBytesAvailable, "char");
% Parse the received packet
[distance1, distance2, distance3, distance4] = parsePacket(packet);
% Display current distances
fprintf(‘Distance from Device 1: %.2f metersn’, distance1);
fprintf(‘Distance from Device 2: %.2f metersn’, distance2);
fprintf(‘Distance from Device 3: %.2f metersn’, distance3);
fprintf(‘Distance from Device 4: %.2f metersn’, distance4);
fprintf(‘n’); % Add newline for clarity
end
pause(0.1);
end
% Clean up
delete(udpReceiver)
function [distance1, distance2, distance3, distance4] = parsePacket(packet)
% Convert packet to string
packetStr = char(packet);
% Split the string by semicolon
data = strsplit(packetStr, ‘;’);
% Initialize distances
distance1 = NaN;
distance2 = NaN;
distance3 = NaN;
distance4 = NaN;
% Parse each part of the data
for i = 1:length(data)
% Split by comma to separate address and distance
parts = strsplit(data{i}, ‘,’);
device = str2double(parts{1});
distance = str2double(parts{2});
% Assign distances based on address
switch device
case 1
distance1 = distance;
case 2
distance2 = distance;
case 3
distance3 = distance;
case 4
distance4 = distance;
end
end
end
Now I want to further process only the respective distances in Simulink. For this, I have converted the code into a Level 2 MATLAB function. Here is the code for it:
function UDP_Receiver(block)
setup(block);
function setup(block)
block.NumInputPorts = 0;
block.NumOutputPorts = 4;
block.SetPreCompInpPortInfoToDynamic;
block.SetPreCompOutPortInfoToDynamic;
block.NumDialogPrms = 0;
block.SampleTimes = [-1 0];
block.SimStateCompliance = ‘DefaultSimState’;
block.RegBlockMethod(‘SetInputPortSamplingMode’, @SetInpPortFrameData);
block.RegBlockMethod(‘Outputs’, @Outputs);
block.RegBlockMethod(‘Terminate’, @Terminate);
% Initialize UDP receiver
% Set output port sampling modes
for i = 1:block.NumOutputPorts
block.OutputPort(i).SamplingMode = ‘Sample’; % Set all output ports to Sample mode
end
block.SetAccelRunOnTLC(true);
function SetInpPortFrameData(block, idx, fd)
block.InputPort(idx).SamplingMode = fd;
for i = 1:block.NumOutputPorts
block.OutputPort(i).SamplingMode = fd;
end
function Outputs(block)
udpreceiver = udpport("LocalPort", 4141);
% Check if UDP receiver is valid
while true
if isvalid(udpreceiver)
% Check if a packet is available
if udpreceiver.NumBytesAvailable > 0
% Read the packet
packet = read(udpreceiver, udpreceiver.NumBytesAvailable, "char");
% Parse the received packet
[distance1, distance2, distance3, distance4] = parsePacket(packet);
% Output distances
block.OutputPort(1).Data = distance1;
block.OutputPort(2).Data = distance2;
block.OutputPort(3).Data = distance3;
block.OutputPort(4).Data = distance4;
end
end
end
function Terminate(block)
% Define a function to parse the received UDP packet
function [distance1, distance2, distance3, distance4] = parsePacket(packet)
% Initialize distances
distance1 = NaN;
distance2 = NaN;
distance3 = NaN;
distance4 = NaN;
% Convert packet to string
packetStr = char(packet);
% Split the string by semicolon
data = strsplit(packetStr, ‘;’);
% Parse each part of the data
for i = 1:length(data)
% Split by comma to separate address and distance
parts = strsplit(data{i}, ‘,’);
if numel(parts) == 2
device = str2double(parts{1});
distance = str2double(parts{2});
% Assign distances based on address
switch device
case 1
distance1 = distance;
case 2
distance2 = distance;
case 3
distance3 = distance;
case 4
distance4 = distance;
end
end
end
Even though it is the same code, the simulation gets terminated or the Data is wrong. What can i do?On an ESP32, I am sending distance data via UDP to MATLAB. There are multiple distances involved, so both the receiver number (from 81 to 84) and the respective distance are transmitted. I can also receive and analyze the data using the following program:
% Set up the UDP receiver
udpReceiver = udpport("LocalPort", 4141);
% Define a function to parse the received UDP packet
% Main loop to continuously receive and display distances
while true
% Check if a packet is available
if udpReceiver.NumBytesAvailable > 0
% Read the packet
packet = read(udpReceiver, udpReceiver.NumBytesAvailable, "char");
% Parse the received packet
[distance1, distance2, distance3, distance4] = parsePacket(packet);
% Display current distances
fprintf(‘Distance from Device 1: %.2f metersn’, distance1);
fprintf(‘Distance from Device 2: %.2f metersn’, distance2);
fprintf(‘Distance from Device 3: %.2f metersn’, distance3);
fprintf(‘Distance from Device 4: %.2f metersn’, distance4);
fprintf(‘n’); % Add newline for clarity
end
pause(0.1);
end
% Clean up
delete(udpReceiver)
function [distance1, distance2, distance3, distance4] = parsePacket(packet)
% Convert packet to string
packetStr = char(packet);
% Split the string by semicolon
data = strsplit(packetStr, ‘;’);
% Initialize distances
distance1 = NaN;
distance2 = NaN;
distance3 = NaN;
distance4 = NaN;
% Parse each part of the data
for i = 1:length(data)
% Split by comma to separate address and distance
parts = strsplit(data{i}, ‘,’);
device = str2double(parts{1});
distance = str2double(parts{2});
% Assign distances based on address
switch device
case 1
distance1 = distance;
case 2
distance2 = distance;
case 3
distance3 = distance;
case 4
distance4 = distance;
end
end
end
Now I want to further process only the respective distances in Simulink. For this, I have converted the code into a Level 2 MATLAB function. Here is the code for it:
function UDP_Receiver(block)
setup(block);
function setup(block)
block.NumInputPorts = 0;
block.NumOutputPorts = 4;
block.SetPreCompInpPortInfoToDynamic;
block.SetPreCompOutPortInfoToDynamic;
block.NumDialogPrms = 0;
block.SampleTimes = [-1 0];
block.SimStateCompliance = ‘DefaultSimState’;
block.RegBlockMethod(‘SetInputPortSamplingMode’, @SetInpPortFrameData);
block.RegBlockMethod(‘Outputs’, @Outputs);
block.RegBlockMethod(‘Terminate’, @Terminate);
% Initialize UDP receiver
% Set output port sampling modes
for i = 1:block.NumOutputPorts
block.OutputPort(i).SamplingMode = ‘Sample’; % Set all output ports to Sample mode
end
block.SetAccelRunOnTLC(true);
function SetInpPortFrameData(block, idx, fd)
block.InputPort(idx).SamplingMode = fd;
for i = 1:block.NumOutputPorts
block.OutputPort(i).SamplingMode = fd;
end
function Outputs(block)
udpreceiver = udpport("LocalPort", 4141);
% Check if UDP receiver is valid
while true
if isvalid(udpreceiver)
% Check if a packet is available
if udpreceiver.NumBytesAvailable > 0
% Read the packet
packet = read(udpreceiver, udpreceiver.NumBytesAvailable, "char");
% Parse the received packet
[distance1, distance2, distance3, distance4] = parsePacket(packet);
% Output distances
block.OutputPort(1).Data = distance1;
block.OutputPort(2).Data = distance2;
block.OutputPort(3).Data = distance3;
block.OutputPort(4).Data = distance4;
end
end
end
function Terminate(block)
% Define a function to parse the received UDP packet
function [distance1, distance2, distance3, distance4] = parsePacket(packet)
% Initialize distances
distance1 = NaN;
distance2 = NaN;
distance3 = NaN;
distance4 = NaN;
% Convert packet to string
packetStr = char(packet);
% Split the string by semicolon
data = strsplit(packetStr, ‘;’);
% Parse each part of the data
for i = 1:length(data)
% Split by comma to separate address and distance
parts = strsplit(data{i}, ‘,’);
if numel(parts) == 2
device = str2double(parts{1});
distance = str2double(parts{2});
% Assign distances based on address
switch device
case 1
distance1 = distance;
case 2
distance2 = distance;
case 3
distance3 = distance;
case 4
distance4 = distance;
end
end
end
Even though it is the same code, the simulation gets terminated or the Data is wrong. What can i do? On an ESP32, I am sending distance data via UDP to MATLAB. There are multiple distances involved, so both the receiver number (from 81 to 84) and the respective distance are transmitted. I can also receive and analyze the data using the following program:
% Set up the UDP receiver
udpReceiver = udpport("LocalPort", 4141);
% Define a function to parse the received UDP packet
% Main loop to continuously receive and display distances
while true
% Check if a packet is available
if udpReceiver.NumBytesAvailable > 0
% Read the packet
packet = read(udpReceiver, udpReceiver.NumBytesAvailable, "char");
% Parse the received packet
[distance1, distance2, distance3, distance4] = parsePacket(packet);
% Display current distances
fprintf(‘Distance from Device 1: %.2f metersn’, distance1);
fprintf(‘Distance from Device 2: %.2f metersn’, distance2);
fprintf(‘Distance from Device 3: %.2f metersn’, distance3);
fprintf(‘Distance from Device 4: %.2f metersn’, distance4);
fprintf(‘n’); % Add newline for clarity
end
pause(0.1);
end
% Clean up
delete(udpReceiver)
function [distance1, distance2, distance3, distance4] = parsePacket(packet)
% Convert packet to string
packetStr = char(packet);
% Split the string by semicolon
data = strsplit(packetStr, ‘;’);
% Initialize distances
distance1 = NaN;
distance2 = NaN;
distance3 = NaN;
distance4 = NaN;
% Parse each part of the data
for i = 1:length(data)
% Split by comma to separate address and distance
parts = strsplit(data{i}, ‘,’);
device = str2double(parts{1});
distance = str2double(parts{2});
% Assign distances based on address
switch device
case 1
distance1 = distance;
case 2
distance2 = distance;
case 3
distance3 = distance;
case 4
distance4 = distance;
end
end
end
Now I want to further process only the respective distances in Simulink. For this, I have converted the code into a Level 2 MATLAB function. Here is the code for it:
function UDP_Receiver(block)
setup(block);
function setup(block)
block.NumInputPorts = 0;
block.NumOutputPorts = 4;
block.SetPreCompInpPortInfoToDynamic;
block.SetPreCompOutPortInfoToDynamic;
block.NumDialogPrms = 0;
block.SampleTimes = [-1 0];
block.SimStateCompliance = ‘DefaultSimState’;
block.RegBlockMethod(‘SetInputPortSamplingMode’, @SetInpPortFrameData);
block.RegBlockMethod(‘Outputs’, @Outputs);
block.RegBlockMethod(‘Terminate’, @Terminate);
% Initialize UDP receiver
% Set output port sampling modes
for i = 1:block.NumOutputPorts
block.OutputPort(i).SamplingMode = ‘Sample’; % Set all output ports to Sample mode
end
block.SetAccelRunOnTLC(true);
function SetInpPortFrameData(block, idx, fd)
block.InputPort(idx).SamplingMode = fd;
for i = 1:block.NumOutputPorts
block.OutputPort(i).SamplingMode = fd;
end
function Outputs(block)
udpreceiver = udpport("LocalPort", 4141);
% Check if UDP receiver is valid
while true
if isvalid(udpreceiver)
% Check if a packet is available
if udpreceiver.NumBytesAvailable > 0
% Read the packet
packet = read(udpreceiver, udpreceiver.NumBytesAvailable, "char");
% Parse the received packet
[distance1, distance2, distance3, distance4] = parsePacket(packet);
% Output distances
block.OutputPort(1).Data = distance1;
block.OutputPort(2).Data = distance2;
block.OutputPort(3).Data = distance3;
block.OutputPort(4).Data = distance4;
end
end
end
function Terminate(block)
% Define a function to parse the received UDP packet
function [distance1, distance2, distance3, distance4] = parsePacket(packet)
% Initialize distances
distance1 = NaN;
distance2 = NaN;
distance3 = NaN;
distance4 = NaN;
% Convert packet to string
packetStr = char(packet);
% Split the string by semicolon
data = strsplit(packetStr, ‘;’);
% Parse each part of the data
for i = 1:length(data)
% Split by comma to separate address and distance
parts = strsplit(data{i}, ‘,’);
if numel(parts) == 2
device = str2double(parts{1});
distance = str2double(parts{2});
% Assign distances based on address
switch device
case 1
distance1 = distance;
case 2
distance2 = distance;
case 3
distance3 = distance;
case 4
distance4 = distance;
end
end
end
Even though it is the same code, the simulation gets terminated or the Data is wrong. What can i do? udp, udp receive, simulink, level2 function MATLAB Answers — New Questions
Structure data obtained from webread
Hi, I would like to have to automatize a procedure to extract data from different URLs, One example of one URL link is the following:
% Generating the URL link
url=’https://earthquake.usgs.gov/fdsnws/event/1/query?format=quakeml&eventid=us6000n8tq’;
% Reading the data
data=webread(url);
The variable “data” contains huge amount of information that I would like to structure in order to access and retrieve data easily without the need of creating a xml file.
I would appreciate the help.Hi, I would like to have to automatize a procedure to extract data from different URLs, One example of one URL link is the following:
% Generating the URL link
url=’https://earthquake.usgs.gov/fdsnws/event/1/query?format=quakeml&eventid=us6000n8tq’;
% Reading the data
data=webread(url);
The variable “data” contains huge amount of information that I would like to structure in order to access and retrieve data easily without the need of creating a xml file.
I would appreciate the help. Hi, I would like to have to automatize a procedure to extract data from different URLs, One example of one URL link is the following:
% Generating the URL link
url=’https://earthquake.usgs.gov/fdsnws/event/1/query?format=quakeml&eventid=us6000n8tq’;
% Reading the data
data=webread(url);
The variable “data” contains huge amount of information that I would like to structure in order to access and retrieve data easily without the need of creating a xml file.
I would appreciate the help. structuring data from webread MATLAB Answers — New Questions
I don’t understand an error message I get that’s related to function ode45.
The error message I get is:
Arrays have incompatible sizes for this operation.
Error in ode45 (line 299)
y5 = y + h .* (b41.*f1 + b42.*f2 + b43.*f3 + b44.*f4 );
I’ve checked my initial condition vector is the correct size. I’m not sure what this error indicated might be wrong in my code.The error message I get is:
Arrays have incompatible sizes for this operation.
Error in ode45 (line 299)
y5 = y + h .* (b41.*f1 + b42.*f2 + b43.*f3 + b44.*f4 );
I’ve checked my initial condition vector is the correct size. I’m not sure what this error indicated might be wrong in my code. The error message I get is:
Arrays have incompatible sizes for this operation.
Error in ode45 (line 299)
y5 = y + h .* (b41.*f1 + b42.*f2 + b43.*f3 + b44.*f4 );
I’ve checked my initial condition vector is the correct size. I’m not sure what this error indicated might be wrong in my code. ode45, matlab MATLAB Answers — New Questions
how can solve this problem : Conversion to cell from double is not possible.
what the error (Error using Untitled18 (line 12)
Conversion to cell from double is not possible.)
% Ensure all columns except the last one are numeric
for i = 1:(width(data) – 1)
if iscell(data{:, i})
data{:, i} = grp2idx(categorical(data{:, i}));
elseif ischar(data{:, i})
data{:, i} = grp2idx(categorical(data{:, i}));
end
endwhat the error (Error using Untitled18 (line 12)
Conversion to cell from double is not possible.)
% Ensure all columns except the last one are numeric
for i = 1:(width(data) – 1)
if iscell(data{:, i})
data{:, i} = grp2idx(categorical(data{:, i}));
elseif ischar(data{:, i})
data{:, i} = grp2idx(categorical(data{:, i}));
end
end what the error (Error using Untitled18 (line 12)
Conversion to cell from double is not possible.)
% Ensure all columns except the last one are numeric
for i = 1:(width(data) – 1)
if iscell(data{:, i})
data{:, i} = grp2idx(categorical(data{:, i}));
elseif ischar(data{:, i})
data{:, i} = grp2idx(categorical(data{:, i}));
end
end axes, optimization MATLAB Answers — New Questions
How to count the number of non-nan values for combination of multiple variables
Hello, I would like to count the number of non-nan values in the d column for unique combinations of a, b and c (i.e I want to generate the e column in tt). If any a,b or c are NaN then the count should be nan as well
% Initial table
a = [1,1,1,2,2,2,2]’
b = [660, 661, 661, 663, 663, NaN, 663]’
c = [1,2,2,5,5,NaN,6]’
d = [11,12,NaN, 13, 14, NaN,5]’
t = table(a,b,c,d)
% Desired output
a = [1,1,1,2,2,2,2]’
b = [660, 661, 661, 663, 663, NaN, 663]’
c = [1,2,2,5,5,NaN,6]’
d = [11,12,NaN, 13, 14, NaN,5]’
e = [1, 1, 1, 2, 2, NaN, 1]’
tt = table(a,b,c,d,e)Hello, I would like to count the number of non-nan values in the d column for unique combinations of a, b and c (i.e I want to generate the e column in tt). If any a,b or c are NaN then the count should be nan as well
% Initial table
a = [1,1,1,2,2,2,2]’
b = [660, 661, 661, 663, 663, NaN, 663]’
c = [1,2,2,5,5,NaN,6]’
d = [11,12,NaN, 13, 14, NaN,5]’
t = table(a,b,c,d)
% Desired output
a = [1,1,1,2,2,2,2]’
b = [660, 661, 661, 663, 663, NaN, 663]’
c = [1,2,2,5,5,NaN,6]’
d = [11,12,NaN, 13, 14, NaN,5]’
e = [1, 1, 1, 2, 2, NaN, 1]’
tt = table(a,b,c,d,e) Hello, I would like to count the number of non-nan values in the d column for unique combinations of a, b and c (i.e I want to generate the e column in tt). If any a,b or c are NaN then the count should be nan as well
% Initial table
a = [1,1,1,2,2,2,2]’
b = [660, 661, 661, 663, 663, NaN, 663]’
c = [1,2,2,5,5,NaN,6]’
d = [11,12,NaN, 13, 14, NaN,5]’
t = table(a,b,c,d)
% Desired output
a = [1,1,1,2,2,2,2]’
b = [660, 661, 661, 663, 663, NaN, 663]’
c = [1,2,2,5,5,NaN,6]’
d = [11,12,NaN, 13, 14, NaN,5]’
e = [1, 1, 1, 2, 2, NaN, 1]’
tt = table(a,b,c,d,e) sum MATLAB Answers — New Questions
Launching MATLAB2024a
Good day,
I have a challenge launching MATLAB2024a. I get an error message of "Why do I get an error of "You do not have a valid license file. How can I resolve this issue?
Your help will be much appreciated.
Kind regards,Good day,
I have a challenge launching MATLAB2024a. I get an error message of "Why do I get an error of "You do not have a valid license file. How can I resolve this issue?
Your help will be much appreciated.
Kind regards, Good day,
I have a challenge launching MATLAB2024a. I get an error message of "Why do I get an error of "You do not have a valid license file. How can I resolve this issue?
Your help will be much appreciated.
Kind regards, matlab, matlab2024a MATLAB Answers — New Questions
i am trying to find coefficients a0 , an and bn but the output for bn seems wrong and will not simplify
i am trying to find coefficients a0 , an and bn but the output for bn seems wrong and will not simplify
i have tried using pretty, symplify, ignoreanalyticconstraint,true and simplifyFraction, but none have worked
f(x) = -3, -pi < x < 0
f(x) = 3, 0 < x < pi
syms t n
T = 2*pi
w0 = 2*pi/T
n=1:5
a0 = (1/T)*int(3,t,-pi,0) + (1/T)*int(-3,t,0,pi)
an = (2/T)*int(-3*cos(n*w0*t),t,-pi,0) + (2/T)*int(3*cos(n*w0*t),t,0,pi)
bn = (2/T)*int(-3*sin(n*w0*t),t,-pi,0) + (2/T)*int(3*sin(n*w0*t),t,0,pi);
pretty(bn)i am trying to find coefficients a0 , an and bn but the output for bn seems wrong and will not simplify
i have tried using pretty, symplify, ignoreanalyticconstraint,true and simplifyFraction, but none have worked
f(x) = -3, -pi < x < 0
f(x) = 3, 0 < x < pi
syms t n
T = 2*pi
w0 = 2*pi/T
n=1:5
a0 = (1/T)*int(3,t,-pi,0) + (1/T)*int(-3,t,0,pi)
an = (2/T)*int(-3*cos(n*w0*t),t,-pi,0) + (2/T)*int(3*cos(n*w0*t),t,0,pi)
bn = (2/T)*int(-3*sin(n*w0*t),t,-pi,0) + (2/T)*int(3*sin(n*w0*t),t,0,pi);
pretty(bn) i am trying to find coefficients a0 , an and bn but the output for bn seems wrong and will not simplify
i have tried using pretty, symplify, ignoreanalyticconstraint,true and simplifyFraction, but none have worked
f(x) = -3, -pi < x < 0
f(x) = 3, 0 < x < pi
syms t n
T = 2*pi
w0 = 2*pi/T
n=1:5
a0 = (1/T)*int(3,t,-pi,0) + (1/T)*int(-3,t,0,pi)
an = (2/T)*int(-3*cos(n*w0*t),t,-pi,0) + (2/T)*int(3*cos(n*w0*t),t,0,pi)
bn = (2/T)*int(-3*sin(n*w0*t),t,-pi,0) + (2/T)*int(3*sin(n*w0*t),t,0,pi);
pretty(bn) fourier, coeffeicients, series, a0, bn, an MATLAB Answers — New Questions
How to include field value in ThingHTTP URL GET Request
I am trying to include a field value in a ThingHTTP GET request but have not been successful.
For example, I have have successfully used
https://myurl.com/site?value=12.34
to send a specifice value to an external site, but was unsuccessful when I tried to send a ThingSpeak channel field value in a similar way. I used the %% method, which works for ThingTweet, but that didn’t seem to work here. e.g.
https://myurl.com/site?value=%%channel_1234567_field_1%%
Am I doing something wrong, or is there an alternative method for doing this?I am trying to include a field value in a ThingHTTP GET request but have not been successful.
For example, I have have successfully used
https://myurl.com/site?value=12.34
to send a specifice value to an external site, but was unsuccessful when I tried to send a ThingSpeak channel field value in a similar way. I used the %% method, which works for ThingTweet, but that didn’t seem to work here. e.g.
https://myurl.com/site?value=%%channel_1234567_field_1%%
Am I doing something wrong, or is there an alternative method for doing this? I am trying to include a field value in a ThingHTTP GET request but have not been successful.
For example, I have have successfully used
https://myurl.com/site?value=12.34
to send a specifice value to an external site, but was unsuccessful when I tried to send a ThingSpeak channel field value in a similar way. I used the %% method, which works for ThingTweet, but that didn’t seem to work here. e.g.
https://myurl.com/site?value=%%channel_1234567_field_1%%
Am I doing something wrong, or is there an alternative method for doing this? thinghttp MATLAB Answers — New Questions
Error using newly added wavelet to wavemngr
I am working with a tool in matlab that matches an orthogonal wavelet to a given prototype signal. The attatched image depicts the information stored within the waveletFilter structure generated by the tool.
I would like to add the f/g filters to wavemngr(). I begin by saving f and calling the .mat file by the wavelet short name I plan to use. I then run the following script:
wsname = ‘L1F’;
wname = ‘L1OptimizedFilter’;
eval([wsname ‘=waveletFilterL1.f/sqrt(2);’]);
save(wsname, wsname);
wavemngr(‘add’, wname, wsname, 1, ”, [wsname ‘.mat’]);
When I use wavemngr(‘read’) to validate the addition of my filter, it is there.
However, when I then proceed to access any information regarding the properties, or use the filter with a given transform, I get an error message saying my filter has not been found.I am working with a tool in matlab that matches an orthogonal wavelet to a given prototype signal. The attatched image depicts the information stored within the waveletFilter structure generated by the tool.
I would like to add the f/g filters to wavemngr(). I begin by saving f and calling the .mat file by the wavelet short name I plan to use. I then run the following script:
wsname = ‘L1F’;
wname = ‘L1OptimizedFilter’;
eval([wsname ‘=waveletFilterL1.f/sqrt(2);’]);
save(wsname, wsname);
wavemngr(‘add’, wname, wsname, 1, ”, [wsname ‘.mat’]);
When I use wavemngr(‘read’) to validate the addition of my filter, it is there.
However, when I then proceed to access any information regarding the properties, or use the filter with a given transform, I get an error message saying my filter has not been found. I am working with a tool in matlab that matches an orthogonal wavelet to a given prototype signal. The attatched image depicts the information stored within the waveletFilter structure generated by the tool.
I would like to add the f/g filters to wavemngr(). I begin by saving f and calling the .mat file by the wavelet short name I plan to use. I then run the following script:
wsname = ‘L1F’;
wname = ‘L1OptimizedFilter’;
eval([wsname ‘=waveletFilterL1.f/sqrt(2);’]);
save(wsname, wsname);
wavemngr(‘add’, wname, wsname, 1, ”, [wsname ‘.mat’]);
When I use wavemngr(‘read’) to validate the addition of my filter, it is there.
However, when I then proceed to access any information regarding the properties, or use the filter with a given transform, I get an error message saying my filter has not been found. wavelet, wavemngr, wpdec MATLAB Answers — New Questions
Error using feval Function to evaluate must be represented as a string scalar, character vector, or function_handle object.
% Example5_5.m
% Solution to Example 5.5. This program calculates and plots
% the concentration of cell mass, concentration of penicillin,
% optimal temperature profile, and adjoint variable of a batch
% penicillin fermentor. It uses the function COLLOCATION to
% solve the set of system and adjoint equations.
clear
clc
clf
% Input data
w = input(‘ Enter w”s as a vector : ‘);
y0 = input(‘ Vector of known initial conditions = ‘);
yf = input(‘ Vector of final conditions = ‘);
guess = input(‘ Vector of guessed initial conditions = ‘);
fname = input(‘n M-file containing the set of differential equations : ‘);
fth = input(‘ M-file containing the necessary condition function : ‘);
n = input(‘ Number of internal collocation points = ‘);
rho = input(‘ Relaxation factor = ‘);
% Solution of the set of differential equations
[t,y] = collocation(fname,0,1,y0,yf,guess,n,rho,[],w,fth);
% Temperature changes
for k = 1:n+2
options=optimset;
theta(k) = fzero(fth,30,options,y(:,k),w);
end
% Plotting the results
subplot(2,2,1), plot(t,y(1,:))
xlabel(‘Time’)
ylabel(‘Cell’)
title(‘(a)’)
subplot(2,2,2), plot(t,y(2,:))
xlabel(‘Time’)
ylabel(‘Penicillin’)
title(‘(b)’)
subplot(2,2,3), plot(t,y(3,:))
xlabel(‘Time’)
ylabel(‘First Adjoint’)
title(‘(c)’)
subplot(2,2,4), plot(t,theta)
xlabel(‘Time’)
ylabel(‘Temperature (deg C)’)
title(‘(d)’)
function f = Ex5_5_func(t,y,w,fth)
% Function Ex5_5_func.M
% This function introduces the set of ordinary differential
% equations used in Example 5.5.
% Temperature
options=optimset;
theta = fzero(fth,30,options,y,w);
% Calculating the b’s
b1 = w(1) * (1-w(2)*(theta-w(3))^2) / (1-w(2)*(25-w(3))^2);
if b1<0, b1=0; end
b2 = w(4) * (1-w(2)*(theta-w(3))^2) / (1-w(2)*(25-w(3))^2);
if b2<0, b2=1e-6; end
b3 = w(5) * (1-w(2)*(theta-w(6))^2) / (1-w(2)*(25-w(6))^2);
if b3<0, b3=0; end
% Evaluating the function values
f(1) = b1*y(1) – b1/b2*y(1)^2;
f(2) = b3*y(1);
f(3) = -b1*y(3) + 2*b1/b2*y(1)*y(3) – b3;
f = f’; % Make it a column vector
function ftheta = Ex5_5_theta(theta,y,w)
% Function Ex5_5_theta.M
% This function calculates the value of the necessary condition
% as a function of the temperature (theta). It is used in solving
% Example 5.5.
% Calculating the b’s
b1 = w(1) * (1-w(2)*(theta-w(3))^2) / (1-w(2)*(25-w(3))^2);
db1 = w(1)*(-w(2))*2*(theta-w(3)) / (1-w(2)*(25-w(3))^2);
b2 = w(4) * (1-w(2)*(theta-w(3))^2) / (1-w(2)*(25-w(3))^2);
db2 = w(4)*(-w(2))*2*(theta-w(3)) / (1-w(2)*(25-w(3))^2);
b3 = w(5) * (1-w(2)*(theta-w(6))^2) / (1-w(2)*(25-w(6))^2);
db3 = w(5)*(-w(2))*2*(theta-w(6)) / (1-w(2)*(25-w(6))^2);
% The function
ftheta = y(3)*(y(1)*db1-y(1)^2*(db1*b2-db2*b1)/b2^2)+y(1)*db3;
function [x,y] = collocation(ODEfile,x0,xf,y0,yf,guess,n,rho,tol,varargin)
%COLLOCATION Solves a boundary value set of ordinary differential
% equations by the orthogonal collocation method.
%
% [X,Y]=COLLOCATION(‘F’,X0,XF,Y0,YF,GAMMA,N) integrates the set of
% ordinary differential equations from X0 to XF by the Nth-degree
% orthogonal collocation method. The equations are contained in
% the M-file F.M. Y0, YF, and GAMMA are the vectors of initial
% conditions, final conditions, and starting guesses respectively.
% The function returns the independent variable in the vector X
% and the set of dependent variables in the matrix Y.
%
% [X,Y]=COLLOCATION(‘F’,X0,XF,Y0,YF,GAMMA,N,RHO,TOL,P1,P2,…)
% uses relaxation factor RHO and tolerance TOL for convergence
% test. Additional parameters P1, P2, … are passed directly to
% the function F. Pass an empty matrix for RHO or TOL to use the
% default value.
%
% See also SHOOTING
% (c) N. Mostoufi & A. Constantinides
% January 1, 1999
% Initialization
if nargin < 7 | isempty(n)
n = 1;
end
if nargin < 8 | isempty(rho)
rho = 1;
end
if nargin < 9 | isempty(tol)
tol = 1e-6;
end
y0 = (y0(:).’)’; % Make sure it’s a column vector
yf = (yf(:).’)’; % Make sure it’s a column vector
guess = (guess(:).’)’; % Make sure it’s a column vector
% Checking the number of guesses
if length(yf) ~= length(guess)
error(‘ The number of guessed conditions is not equal to the number of final conditions.’)
end
r = length(y0); % Number of initial conditions
m = r + length(yf); % Number of boundary conditions
% Checking the number of equations
ftest = feval(ODEfile,x0,[y0 ; guess],varargin{:});
if length(ftest) ~= m
error(‘ The number of equations is not equal to the number of boundary conditions.’)
end
fprintf(‘n Integrating. Please wait.nn’)
% Coefficients of the Legendre polynomial
for k = 0 : n/2
cl(2*k+1) = (-1)^k * gamma(2*n-2*k+1) / …
(2^n * gamma(k+1) * gamma(n-k+1) * gamma(n-2*k+1));
if k < n/2
cl(2*k+2) = 0;
end
end
zl = roots(cl); % Roots of the Legendre polynomial
z = [-1; sort(zl); 1]; % Collocation points (z)
x = (xf-x0)*z/2+(xf+x0)/2; % Collocation points (x)
% Bulding the vector of starting values of the dependent variables
[p,q] = RK(ODEfile,x0,xf,(xf-x0)/20,[y0 ; guess],2,varargin{:});
for k = 1:m
y(k,:) = spline(p,q(k,:),x’);
end
y(r+1:m,end) = yf(1:m-r);
% Building the matrix A
Q(:,1) = ones(n+2,1);
C(:,1) = zeros(n+2,1);
for i = 1:n+1
Q(:,i+1) = x.^i;
C(:,i+1) = i*x.^(i-1);
end
A = C*inv(Q);
for k = 1:m
k1 = (k-1)*(n+2)+1;
k2 = k1 + n+1;
Am(k1:k2,k1:k2) = A; % Building the matrix Am
Y(k1:k2) = y(k,:); % Building the vector Y
end
Y = Y’; % Make it a column vector
Y1 = Y * 1.1;
iter = 0;
maxiter = 100;
F = zeros(m*(n+2),1);
Fa = zeros(m*(n+2),1);
dY = zeros(m*(n+2),1);
position = []; % Collocation points excluding boundary conditions
for k = 1:m
if k <= r
position = [position, (k-1)*(n+2)+[2:n+2] ];
else
position = [position, (k-1)*(n+2)+[1:n+1] ];
end
end
% Newton’s method
while max(abs(Y1 – Y)) > tol & iter < maxiter
iter = iter + 1;
fprintf(‘ Iteration %3dn’,iter)
Y1 = Y;
% Building the vector F
for k = 1:n+2
F(k : n+2 : (m-1)*(n+2)+k) = …
feval(ODEfile,x(k),Y(k : n+2 : (m-1)*(n+2)+k),varargin{:});
end
fnk = Am * Y – F;
% Set dY for derivation
for k = 1:m*(n+1)
if Y(position(k)) ~= 0
dY(position(k)) = Y(position(k)) / 100;
else
dY(position(k)) = 0.01;
end
end
% Calculation of the Jacobian matrix
for k = 1:m
for kk = 1:n+1
a = Y;
nc = (k-1)*(n+1)+kk;
a(position(nc)) = Y(position(nc)) + dY(position(nc));
for kkk = 1:n+2
Fa(kkk : n+2 : (m-1)*(n+2)+kkk) = …
feval(ODEfile,x(kkk),a(kkk:n+2:(m-1)*(n+2)+kkk),varargin{:});
end
fnka = Am * a – Fa;
jacob(:,nc) = (fnka(position) – fnk(position))…
/ dY(position(nc));
end
end
% Next approximation of the roots
if det(jacob) == 0
Y(position) = Y(position) + max([abs(dY(position)); 1.1*tol]);
else
Y(position) = Y(position) – rho * inv(jacob) * fnk(position);
end
end
% Rearranging the y’s
for k = 1:m
k1 = (k-1)*(n+2)+1;
k2 = k1 + n+1;
y(k,:) = Y(k1:k2)’;
end
x = x’;
if iter >= maxiter
disp(‘Warning : Maximum iterations reached.’)
end% Example5_5.m
% Solution to Example 5.5. This program calculates and plots
% the concentration of cell mass, concentration of penicillin,
% optimal temperature profile, and adjoint variable of a batch
% penicillin fermentor. It uses the function COLLOCATION to
% solve the set of system and adjoint equations.
clear
clc
clf
% Input data
w = input(‘ Enter w”s as a vector : ‘);
y0 = input(‘ Vector of known initial conditions = ‘);
yf = input(‘ Vector of final conditions = ‘);
guess = input(‘ Vector of guessed initial conditions = ‘);
fname = input(‘n M-file containing the set of differential equations : ‘);
fth = input(‘ M-file containing the necessary condition function : ‘);
n = input(‘ Number of internal collocation points = ‘);
rho = input(‘ Relaxation factor = ‘);
% Solution of the set of differential equations
[t,y] = collocation(fname,0,1,y0,yf,guess,n,rho,[],w,fth);
% Temperature changes
for k = 1:n+2
options=optimset;
theta(k) = fzero(fth,30,options,y(:,k),w);
end
% Plotting the results
subplot(2,2,1), plot(t,y(1,:))
xlabel(‘Time’)
ylabel(‘Cell’)
title(‘(a)’)
subplot(2,2,2), plot(t,y(2,:))
xlabel(‘Time’)
ylabel(‘Penicillin’)
title(‘(b)’)
subplot(2,2,3), plot(t,y(3,:))
xlabel(‘Time’)
ylabel(‘First Adjoint’)
title(‘(c)’)
subplot(2,2,4), plot(t,theta)
xlabel(‘Time’)
ylabel(‘Temperature (deg C)’)
title(‘(d)’)
function f = Ex5_5_func(t,y,w,fth)
% Function Ex5_5_func.M
% This function introduces the set of ordinary differential
% equations used in Example 5.5.
% Temperature
options=optimset;
theta = fzero(fth,30,options,y,w);
% Calculating the b’s
b1 = w(1) * (1-w(2)*(theta-w(3))^2) / (1-w(2)*(25-w(3))^2);
if b1<0, b1=0; end
b2 = w(4) * (1-w(2)*(theta-w(3))^2) / (1-w(2)*(25-w(3))^2);
if b2<0, b2=1e-6; end
b3 = w(5) * (1-w(2)*(theta-w(6))^2) / (1-w(2)*(25-w(6))^2);
if b3<0, b3=0; end
% Evaluating the function values
f(1) = b1*y(1) – b1/b2*y(1)^2;
f(2) = b3*y(1);
f(3) = -b1*y(3) + 2*b1/b2*y(1)*y(3) – b3;
f = f’; % Make it a column vector
function ftheta = Ex5_5_theta(theta,y,w)
% Function Ex5_5_theta.M
% This function calculates the value of the necessary condition
% as a function of the temperature (theta). It is used in solving
% Example 5.5.
% Calculating the b’s
b1 = w(1) * (1-w(2)*(theta-w(3))^2) / (1-w(2)*(25-w(3))^2);
db1 = w(1)*(-w(2))*2*(theta-w(3)) / (1-w(2)*(25-w(3))^2);
b2 = w(4) * (1-w(2)*(theta-w(3))^2) / (1-w(2)*(25-w(3))^2);
db2 = w(4)*(-w(2))*2*(theta-w(3)) / (1-w(2)*(25-w(3))^2);
b3 = w(5) * (1-w(2)*(theta-w(6))^2) / (1-w(2)*(25-w(6))^2);
db3 = w(5)*(-w(2))*2*(theta-w(6)) / (1-w(2)*(25-w(6))^2);
% The function
ftheta = y(3)*(y(1)*db1-y(1)^2*(db1*b2-db2*b1)/b2^2)+y(1)*db3;
function [x,y] = collocation(ODEfile,x0,xf,y0,yf,guess,n,rho,tol,varargin)
%COLLOCATION Solves a boundary value set of ordinary differential
% equations by the orthogonal collocation method.
%
% [X,Y]=COLLOCATION(‘F’,X0,XF,Y0,YF,GAMMA,N) integrates the set of
% ordinary differential equations from X0 to XF by the Nth-degree
% orthogonal collocation method. The equations are contained in
% the M-file F.M. Y0, YF, and GAMMA are the vectors of initial
% conditions, final conditions, and starting guesses respectively.
% The function returns the independent variable in the vector X
% and the set of dependent variables in the matrix Y.
%
% [X,Y]=COLLOCATION(‘F’,X0,XF,Y0,YF,GAMMA,N,RHO,TOL,P1,P2,…)
% uses relaxation factor RHO and tolerance TOL for convergence
% test. Additional parameters P1, P2, … are passed directly to
% the function F. Pass an empty matrix for RHO or TOL to use the
% default value.
%
% See also SHOOTING
% (c) N. Mostoufi & A. Constantinides
% January 1, 1999
% Initialization
if nargin < 7 | isempty(n)
n = 1;
end
if nargin < 8 | isempty(rho)
rho = 1;
end
if nargin < 9 | isempty(tol)
tol = 1e-6;
end
y0 = (y0(:).’)’; % Make sure it’s a column vector
yf = (yf(:).’)’; % Make sure it’s a column vector
guess = (guess(:).’)’; % Make sure it’s a column vector
% Checking the number of guesses
if length(yf) ~= length(guess)
error(‘ The number of guessed conditions is not equal to the number of final conditions.’)
end
r = length(y0); % Number of initial conditions
m = r + length(yf); % Number of boundary conditions
% Checking the number of equations
ftest = feval(ODEfile,x0,[y0 ; guess],varargin{:});
if length(ftest) ~= m
error(‘ The number of equations is not equal to the number of boundary conditions.’)
end
fprintf(‘n Integrating. Please wait.nn’)
% Coefficients of the Legendre polynomial
for k = 0 : n/2
cl(2*k+1) = (-1)^k * gamma(2*n-2*k+1) / …
(2^n * gamma(k+1) * gamma(n-k+1) * gamma(n-2*k+1));
if k < n/2
cl(2*k+2) = 0;
end
end
zl = roots(cl); % Roots of the Legendre polynomial
z = [-1; sort(zl); 1]; % Collocation points (z)
x = (xf-x0)*z/2+(xf+x0)/2; % Collocation points (x)
% Bulding the vector of starting values of the dependent variables
[p,q] = RK(ODEfile,x0,xf,(xf-x0)/20,[y0 ; guess],2,varargin{:});
for k = 1:m
y(k,:) = spline(p,q(k,:),x’);
end
y(r+1:m,end) = yf(1:m-r);
% Building the matrix A
Q(:,1) = ones(n+2,1);
C(:,1) = zeros(n+2,1);
for i = 1:n+1
Q(:,i+1) = x.^i;
C(:,i+1) = i*x.^(i-1);
end
A = C*inv(Q);
for k = 1:m
k1 = (k-1)*(n+2)+1;
k2 = k1 + n+1;
Am(k1:k2,k1:k2) = A; % Building the matrix Am
Y(k1:k2) = y(k,:); % Building the vector Y
end
Y = Y’; % Make it a column vector
Y1 = Y * 1.1;
iter = 0;
maxiter = 100;
F = zeros(m*(n+2),1);
Fa = zeros(m*(n+2),1);
dY = zeros(m*(n+2),1);
position = []; % Collocation points excluding boundary conditions
for k = 1:m
if k <= r
position = [position, (k-1)*(n+2)+[2:n+2] ];
else
position = [position, (k-1)*(n+2)+[1:n+1] ];
end
end
% Newton’s method
while max(abs(Y1 – Y)) > tol & iter < maxiter
iter = iter + 1;
fprintf(‘ Iteration %3dn’,iter)
Y1 = Y;
% Building the vector F
for k = 1:n+2
F(k : n+2 : (m-1)*(n+2)+k) = …
feval(ODEfile,x(k),Y(k : n+2 : (m-1)*(n+2)+k),varargin{:});
end
fnk = Am * Y – F;
% Set dY for derivation
for k = 1:m*(n+1)
if Y(position(k)) ~= 0
dY(position(k)) = Y(position(k)) / 100;
else
dY(position(k)) = 0.01;
end
end
% Calculation of the Jacobian matrix
for k = 1:m
for kk = 1:n+1
a = Y;
nc = (k-1)*(n+1)+kk;
a(position(nc)) = Y(position(nc)) + dY(position(nc));
for kkk = 1:n+2
Fa(kkk : n+2 : (m-1)*(n+2)+kkk) = …
feval(ODEfile,x(kkk),a(kkk:n+2:(m-1)*(n+2)+kkk),varargin{:});
end
fnka = Am * a – Fa;
jacob(:,nc) = (fnka(position) – fnk(position))…
/ dY(position(nc));
end
end
% Next approximation of the roots
if det(jacob) == 0
Y(position) = Y(position) + max([abs(dY(position)); 1.1*tol]);
else
Y(position) = Y(position) – rho * inv(jacob) * fnk(position);
end
end
% Rearranging the y’s
for k = 1:m
k1 = (k-1)*(n+2)+1;
k2 = k1 + n+1;
y(k,:) = Y(k1:k2)’;
end
x = x’;
if iter >= maxiter
disp(‘Warning : Maximum iterations reached.’)
end % Example5_5.m
% Solution to Example 5.5. This program calculates and plots
% the concentration of cell mass, concentration of penicillin,
% optimal temperature profile, and adjoint variable of a batch
% penicillin fermentor. It uses the function COLLOCATION to
% solve the set of system and adjoint equations.
clear
clc
clf
% Input data
w = input(‘ Enter w”s as a vector : ‘);
y0 = input(‘ Vector of known initial conditions = ‘);
yf = input(‘ Vector of final conditions = ‘);
guess = input(‘ Vector of guessed initial conditions = ‘);
fname = input(‘n M-file containing the set of differential equations : ‘);
fth = input(‘ M-file containing the necessary condition function : ‘);
n = input(‘ Number of internal collocation points = ‘);
rho = input(‘ Relaxation factor = ‘);
% Solution of the set of differential equations
[t,y] = collocation(fname,0,1,y0,yf,guess,n,rho,[],w,fth);
% Temperature changes
for k = 1:n+2
options=optimset;
theta(k) = fzero(fth,30,options,y(:,k),w);
end
% Plotting the results
subplot(2,2,1), plot(t,y(1,:))
xlabel(‘Time’)
ylabel(‘Cell’)
title(‘(a)’)
subplot(2,2,2), plot(t,y(2,:))
xlabel(‘Time’)
ylabel(‘Penicillin’)
title(‘(b)’)
subplot(2,2,3), plot(t,y(3,:))
xlabel(‘Time’)
ylabel(‘First Adjoint’)
title(‘(c)’)
subplot(2,2,4), plot(t,theta)
xlabel(‘Time’)
ylabel(‘Temperature (deg C)’)
title(‘(d)’)
function f = Ex5_5_func(t,y,w,fth)
% Function Ex5_5_func.M
% This function introduces the set of ordinary differential
% equations used in Example 5.5.
% Temperature
options=optimset;
theta = fzero(fth,30,options,y,w);
% Calculating the b’s
b1 = w(1) * (1-w(2)*(theta-w(3))^2) / (1-w(2)*(25-w(3))^2);
if b1<0, b1=0; end
b2 = w(4) * (1-w(2)*(theta-w(3))^2) / (1-w(2)*(25-w(3))^2);
if b2<0, b2=1e-6; end
b3 = w(5) * (1-w(2)*(theta-w(6))^2) / (1-w(2)*(25-w(6))^2);
if b3<0, b3=0; end
% Evaluating the function values
f(1) = b1*y(1) – b1/b2*y(1)^2;
f(2) = b3*y(1);
f(3) = -b1*y(3) + 2*b1/b2*y(1)*y(3) – b3;
f = f’; % Make it a column vector
function ftheta = Ex5_5_theta(theta,y,w)
% Function Ex5_5_theta.M
% This function calculates the value of the necessary condition
% as a function of the temperature (theta). It is used in solving
% Example 5.5.
% Calculating the b’s
b1 = w(1) * (1-w(2)*(theta-w(3))^2) / (1-w(2)*(25-w(3))^2);
db1 = w(1)*(-w(2))*2*(theta-w(3)) / (1-w(2)*(25-w(3))^2);
b2 = w(4) * (1-w(2)*(theta-w(3))^2) / (1-w(2)*(25-w(3))^2);
db2 = w(4)*(-w(2))*2*(theta-w(3)) / (1-w(2)*(25-w(3))^2);
b3 = w(5) * (1-w(2)*(theta-w(6))^2) / (1-w(2)*(25-w(6))^2);
db3 = w(5)*(-w(2))*2*(theta-w(6)) / (1-w(2)*(25-w(6))^2);
% The function
ftheta = y(3)*(y(1)*db1-y(1)^2*(db1*b2-db2*b1)/b2^2)+y(1)*db3;
function [x,y] = collocation(ODEfile,x0,xf,y0,yf,guess,n,rho,tol,varargin)
%COLLOCATION Solves a boundary value set of ordinary differential
% equations by the orthogonal collocation method.
%
% [X,Y]=COLLOCATION(‘F’,X0,XF,Y0,YF,GAMMA,N) integrates the set of
% ordinary differential equations from X0 to XF by the Nth-degree
% orthogonal collocation method. The equations are contained in
% the M-file F.M. Y0, YF, and GAMMA are the vectors of initial
% conditions, final conditions, and starting guesses respectively.
% The function returns the independent variable in the vector X
% and the set of dependent variables in the matrix Y.
%
% [X,Y]=COLLOCATION(‘F’,X0,XF,Y0,YF,GAMMA,N,RHO,TOL,P1,P2,…)
% uses relaxation factor RHO and tolerance TOL for convergence
% test. Additional parameters P1, P2, … are passed directly to
% the function F. Pass an empty matrix for RHO or TOL to use the
% default value.
%
% See also SHOOTING
% (c) N. Mostoufi & A. Constantinides
% January 1, 1999
% Initialization
if nargin < 7 | isempty(n)
n = 1;
end
if nargin < 8 | isempty(rho)
rho = 1;
end
if nargin < 9 | isempty(tol)
tol = 1e-6;
end
y0 = (y0(:).’)’; % Make sure it’s a column vector
yf = (yf(:).’)’; % Make sure it’s a column vector
guess = (guess(:).’)’; % Make sure it’s a column vector
% Checking the number of guesses
if length(yf) ~= length(guess)
error(‘ The number of guessed conditions is not equal to the number of final conditions.’)
end
r = length(y0); % Number of initial conditions
m = r + length(yf); % Number of boundary conditions
% Checking the number of equations
ftest = feval(ODEfile,x0,[y0 ; guess],varargin{:});
if length(ftest) ~= m
error(‘ The number of equations is not equal to the number of boundary conditions.’)
end
fprintf(‘n Integrating. Please wait.nn’)
% Coefficients of the Legendre polynomial
for k = 0 : n/2
cl(2*k+1) = (-1)^k * gamma(2*n-2*k+1) / …
(2^n * gamma(k+1) * gamma(n-k+1) * gamma(n-2*k+1));
if k < n/2
cl(2*k+2) = 0;
end
end
zl = roots(cl); % Roots of the Legendre polynomial
z = [-1; sort(zl); 1]; % Collocation points (z)
x = (xf-x0)*z/2+(xf+x0)/2; % Collocation points (x)
% Bulding the vector of starting values of the dependent variables
[p,q] = RK(ODEfile,x0,xf,(xf-x0)/20,[y0 ; guess],2,varargin{:});
for k = 1:m
y(k,:) = spline(p,q(k,:),x’);
end
y(r+1:m,end) = yf(1:m-r);
% Building the matrix A
Q(:,1) = ones(n+2,1);
C(:,1) = zeros(n+2,1);
for i = 1:n+1
Q(:,i+1) = x.^i;
C(:,i+1) = i*x.^(i-1);
end
A = C*inv(Q);
for k = 1:m
k1 = (k-1)*(n+2)+1;
k2 = k1 + n+1;
Am(k1:k2,k1:k2) = A; % Building the matrix Am
Y(k1:k2) = y(k,:); % Building the vector Y
end
Y = Y’; % Make it a column vector
Y1 = Y * 1.1;
iter = 0;
maxiter = 100;
F = zeros(m*(n+2),1);
Fa = zeros(m*(n+2),1);
dY = zeros(m*(n+2),1);
position = []; % Collocation points excluding boundary conditions
for k = 1:m
if k <= r
position = [position, (k-1)*(n+2)+[2:n+2] ];
else
position = [position, (k-1)*(n+2)+[1:n+1] ];
end
end
% Newton’s method
while max(abs(Y1 – Y)) > tol & iter < maxiter
iter = iter + 1;
fprintf(‘ Iteration %3dn’,iter)
Y1 = Y;
% Building the vector F
for k = 1:n+2
F(k : n+2 : (m-1)*(n+2)+k) = …
feval(ODEfile,x(k),Y(k : n+2 : (m-1)*(n+2)+k),varargin{:});
end
fnk = Am * Y – F;
% Set dY for derivation
for k = 1:m*(n+1)
if Y(position(k)) ~= 0
dY(position(k)) = Y(position(k)) / 100;
else
dY(position(k)) = 0.01;
end
end
% Calculation of the Jacobian matrix
for k = 1:m
for kk = 1:n+1
a = Y;
nc = (k-1)*(n+1)+kk;
a(position(nc)) = Y(position(nc)) + dY(position(nc));
for kkk = 1:n+2
Fa(kkk : n+2 : (m-1)*(n+2)+kkk) = …
feval(ODEfile,x(kkk),a(kkk:n+2:(m-1)*(n+2)+kkk),varargin{:});
end
fnka = Am * a – Fa;
jacob(:,nc) = (fnka(position) – fnk(position))…
/ dY(position(nc));
end
end
% Next approximation of the roots
if det(jacob) == 0
Y(position) = Y(position) + max([abs(dY(position)); 1.1*tol]);
else
Y(position) = Y(position) – rho * inv(jacob) * fnk(position);
end
end
% Rearranging the y’s
for k = 1:m
k1 = (k-1)*(n+2)+1;
k2 = k1 + n+1;
y(k,:) = Y(k1:k2)’;
end
x = x’;
if iter >= maxiter
disp(‘Warning : Maximum iterations reached.’)
end collocation MATLAB Answers — New Questions
THD analysis of mathematical simulink model
I have done mathematical modelling of my system in simulink then how to perform the THD analysisI have done mathematical modelling of my system in simulink then how to perform the THD analysis I have done mathematical modelling of my system in simulink then how to perform the THD analysis thd, mathematical model MATLAB Answers — New Questions
How to plot RGB histogram of an image into a single 3D slice plot?
Hello. Im working on color image encryption and need to plot the histogram for each color channels. I can plot the individual color channel histogram in three 2D plot with this code.
close all;
image = imread(‘peppers.png’);
R = image(:,:,1);
G = image(:,:,2);
B = image(:,:,3);
[Width,Length] = size(image);
subplot(2,2,1); imshow(image);
title(‘Plain Image’)
subplot(2,2,2);
imhist(R);
myHist1 = findobj(gca, ‘Type’, ‘Stem’);
myHist1.Color = [1 0 0];
title(‘Red Channel Plain Histogram’)
subplot(2,2,3);
imhist(G);
myHist2 = findobj(gca, ‘Type’, ‘Stem’);
myHist2.Color = [0 1 0];
title(‘Green Channel Plain Histogram’)
subplot(2,2,4);
imhist(B);
myHist3 = findobj(gca, ‘Type’, ‘Stem’);
myHist3.Color = [0 0 1];
xlim([0 256]);
title(‘Blue Channel Plain Histogram’)
But, i tried to plot them together in a 3D plot like this below (picture from an article i found), but i cant. I tried to find any forum that talks about this, but i can only found slice plots of meshgrid, not from histogram.
If anyone could help, I would appreciate it so much.
Thank you!Hello. Im working on color image encryption and need to plot the histogram for each color channels. I can plot the individual color channel histogram in three 2D plot with this code.
close all;
image = imread(‘peppers.png’);
R = image(:,:,1);
G = image(:,:,2);
B = image(:,:,3);
[Width,Length] = size(image);
subplot(2,2,1); imshow(image);
title(‘Plain Image’)
subplot(2,2,2);
imhist(R);
myHist1 = findobj(gca, ‘Type’, ‘Stem’);
myHist1.Color = [1 0 0];
title(‘Red Channel Plain Histogram’)
subplot(2,2,3);
imhist(G);
myHist2 = findobj(gca, ‘Type’, ‘Stem’);
myHist2.Color = [0 1 0];
title(‘Green Channel Plain Histogram’)
subplot(2,2,4);
imhist(B);
myHist3 = findobj(gca, ‘Type’, ‘Stem’);
myHist3.Color = [0 0 1];
xlim([0 256]);
title(‘Blue Channel Plain Histogram’)
But, i tried to plot them together in a 3D plot like this below (picture from an article i found), but i cant. I tried to find any forum that talks about this, but i can only found slice plots of meshgrid, not from histogram.
If anyone could help, I would appreciate it so much.
Thank you! Hello. Im working on color image encryption and need to plot the histogram for each color channels. I can plot the individual color channel histogram in three 2D plot with this code.
close all;
image = imread(‘peppers.png’);
R = image(:,:,1);
G = image(:,:,2);
B = image(:,:,3);
[Width,Length] = size(image);
subplot(2,2,1); imshow(image);
title(‘Plain Image’)
subplot(2,2,2);
imhist(R);
myHist1 = findobj(gca, ‘Type’, ‘Stem’);
myHist1.Color = [1 0 0];
title(‘Red Channel Plain Histogram’)
subplot(2,2,3);
imhist(G);
myHist2 = findobj(gca, ‘Type’, ‘Stem’);
myHist2.Color = [0 1 0];
title(‘Green Channel Plain Histogram’)
subplot(2,2,4);
imhist(B);
myHist3 = findobj(gca, ‘Type’, ‘Stem’);
myHist3.Color = [0 0 1];
xlim([0 256]);
title(‘Blue Channel Plain Histogram’)
But, i tried to plot them together in a 3D plot like this below (picture from an article i found), but i cant. I tried to find any forum that talks about this, but i can only found slice plots of meshgrid, not from histogram.
If anyone could help, I would appreciate it so much.
Thank you! image processing, histogram, 3d plots MATLAB Answers — New Questions
Plot histogram of a series of images and extract cracks
Dear all,
I’m trying to plot histogram of a series of tomography images to assess the threshold for extracting cracks. I don’t understand why the histogram is not displayed. I would like to select at least the first and the last images to determine the threshold. Here is the code:
Thanks a lot for any help
clear all
close all
clc
a= load(‘tomo_carota_8bit.mat’)
x=a.x_8;
x=double(x);
% clear a
%%
figure,
for ii = 1:size(x, 3)
ii
I = squeeze(x(:,:,ii));
imshow(I, []);
pause(0.1)
end
subplot(3,2,1);
imshow(I,[]);
title(‘Original Grayscale Image’, ‘FontSize’, 15);
subplot(3,2,2);
imhist(I);
title(‘Histogram of original image’);
subplot(3,2,3);
imhist(I);
[counts, grayLevels] = imhist(I);
bar(grayLevels, counts, ‘EdgeColor’, ‘r’, ‘FaceColor’, ‘b’, ‘BarWidth’, 1);
xlim([0, max(I(:))]);
%xlim([0 100])
title(‘Histogram of original image zoomed’);
subplot(3,2,4);
thresholdValue = 85;
thresholdValue1 = 60;
f.InvertHardcopy = ‘off’;
binaryImage1 = I > thresholdValue1;
imshow(binaryImage1, []);
title(‘Binary Image threshold 85’);
f.InvertHardcopy = ‘off’;
binaryImage = I > thresholdValue;
subplot(3,2,5);
imshow(binaryImage, []);
title(‘Binary Image threshold 60’);
figure (1)Dear all,
I’m trying to plot histogram of a series of tomography images to assess the threshold for extracting cracks. I don’t understand why the histogram is not displayed. I would like to select at least the first and the last images to determine the threshold. Here is the code:
Thanks a lot for any help
clear all
close all
clc
a= load(‘tomo_carota_8bit.mat’)
x=a.x_8;
x=double(x);
% clear a
%%
figure,
for ii = 1:size(x, 3)
ii
I = squeeze(x(:,:,ii));
imshow(I, []);
pause(0.1)
end
subplot(3,2,1);
imshow(I,[]);
title(‘Original Grayscale Image’, ‘FontSize’, 15);
subplot(3,2,2);
imhist(I);
title(‘Histogram of original image’);
subplot(3,2,3);
imhist(I);
[counts, grayLevels] = imhist(I);
bar(grayLevels, counts, ‘EdgeColor’, ‘r’, ‘FaceColor’, ‘b’, ‘BarWidth’, 1);
xlim([0, max(I(:))]);
%xlim([0 100])
title(‘Histogram of original image zoomed’);
subplot(3,2,4);
thresholdValue = 85;
thresholdValue1 = 60;
f.InvertHardcopy = ‘off’;
binaryImage1 = I > thresholdValue1;
imshow(binaryImage1, []);
title(‘Binary Image threshold 85’);
f.InvertHardcopy = ‘off’;
binaryImage = I > thresholdValue;
subplot(3,2,5);
imshow(binaryImage, []);
title(‘Binary Image threshold 60’);
figure (1) Dear all,
I’m trying to plot histogram of a series of tomography images to assess the threshold for extracting cracks. I don’t understand why the histogram is not displayed. I would like to select at least the first and the last images to determine the threshold. Here is the code:
Thanks a lot for any help
clear all
close all
clc
a= load(‘tomo_carota_8bit.mat’)
x=a.x_8;
x=double(x);
% clear a
%%
figure,
for ii = 1:size(x, 3)
ii
I = squeeze(x(:,:,ii));
imshow(I, []);
pause(0.1)
end
subplot(3,2,1);
imshow(I,[]);
title(‘Original Grayscale Image’, ‘FontSize’, 15);
subplot(3,2,2);
imhist(I);
title(‘Histogram of original image’);
subplot(3,2,3);
imhist(I);
[counts, grayLevels] = imhist(I);
bar(grayLevels, counts, ‘EdgeColor’, ‘r’, ‘FaceColor’, ‘b’, ‘BarWidth’, 1);
xlim([0, max(I(:))]);
%xlim([0 100])
title(‘Histogram of original image zoomed’);
subplot(3,2,4);
thresholdValue = 85;
thresholdValue1 = 60;
f.InvertHardcopy = ‘off’;
binaryImage1 = I > thresholdValue1;
imshow(binaryImage1, []);
title(‘Binary Image threshold 85’);
f.InvertHardcopy = ‘off’;
binaryImage = I > thresholdValue;
subplot(3,2,5);
imshow(binaryImage, []);
title(‘Binary Image threshold 60’);
figure (1) threshold, imhist, imshow MATLAB Answers — New Questions
How does the Spacecraft Dynamics block work?
In Simulink (Aerospace Blockset) there is a Spacecraft Dynamics block. How does he work? I can’t look inside it (Look Under Mask option is inactive). The description page shows the equations that are used in the block, but the numbers given are clearly not given in full (it seems to me). https://www.mathworks.com/help/aeroblks/getting-started-with-the-spacecraft-dynamics-block.html
In addition, the equations themselves raise some questions, for example, the PDEs are given. Simulink can now solve PDEs in real time?
I want to understand how this block works in order to learn how to write my own to suit my own needs.In Simulink (Aerospace Blockset) there is a Spacecraft Dynamics block. How does he work? I can’t look inside it (Look Under Mask option is inactive). The description page shows the equations that are used in the block, but the numbers given are clearly not given in full (it seems to me). https://www.mathworks.com/help/aeroblks/getting-started-with-the-spacecraft-dynamics-block.html
In addition, the equations themselves raise some questions, for example, the PDEs are given. Simulink can now solve PDEs in real time?
I want to understand how this block works in order to learn how to write my own to suit my own needs. In Simulink (Aerospace Blockset) there is a Spacecraft Dynamics block. How does he work? I can’t look inside it (Look Under Mask option is inactive). The description page shows the equations that are used in the block, but the numbers given are clearly not given in full (it seems to me). https://www.mathworks.com/help/aeroblks/getting-started-with-the-spacecraft-dynamics-block.html
In addition, the equations themselves raise some questions, for example, the PDEs are given. Simulink can now solve PDEs in real time?
I want to understand how this block works in order to learn how to write my own to suit my own needs. aerospace blockset, spacecraft dynamics, simulink MATLAB Answers — New Questions