Category: Matlab
Category Archives: Matlab
Automated bad SEGMENT detection in EEGLAB
Hello everyone,
I am new to EEG pre-processing. I wanted to know if there is any way to detect bad segments in the EEG data automatically in EEGLAB? I found resources for automated detection of bad channels and arifact detection and rejection using ICLabel. However, i do not find any for bad segment detection and rejection. I have a lot of data and manually detecting it will be very time consuming. I heard about AMICA. But it seems to do ICA decomposition and I am satified with runica. If I am not wrong, AMICA doesnt detect bad segments.
Looking forward to your insights.Hello everyone,
I am new to EEG pre-processing. I wanted to know if there is any way to detect bad segments in the EEG data automatically in EEGLAB? I found resources for automated detection of bad channels and arifact detection and rejection using ICLabel. However, i do not find any for bad segment detection and rejection. I have a lot of data and manually detecting it will be very time consuming. I heard about AMICA. But it seems to do ICA decomposition and I am satified with runica. If I am not wrong, AMICA doesnt detect bad segments.
Looking forward to your insights. Hello everyone,
I am new to EEG pre-processing. I wanted to know if there is any way to detect bad segments in the EEG data automatically in EEGLAB? I found resources for automated detection of bad channels and arifact detection and rejection using ICLabel. However, i do not find any for bad segment detection and rejection. I have a lot of data and manually detecting it will be very time consuming. I heard about AMICA. But it seems to do ICA decomposition and I am satified with runica. If I am not wrong, AMICA doesnt detect bad segments.
Looking forward to your insights. amica, preprocessing, bad segment, eeglab MATLAB Answers — New Questions
To take the partial derivative of a function using matlab
Here is a particular code. Can anyone please help me in taking the analytical (partial) derivative of the function ‘F’ along X (i.e., w.r.t. X) along Y (i.e., w.r.t. Y) and along the diagonal (i.e., w.r.t. X plus w.r.t. Y) using matlab command.
[X, Y]=meshgrid(-1:2/511:+1, -1:2/511:+1);
F=sqrt(3).*(2.*(X.^2+Y.^2)-1);
Thanking You!Here is a particular code. Can anyone please help me in taking the analytical (partial) derivative of the function ‘F’ along X (i.e., w.r.t. X) along Y (i.e., w.r.t. Y) and along the diagonal (i.e., w.r.t. X plus w.r.t. Y) using matlab command.
[X, Y]=meshgrid(-1:2/511:+1, -1:2/511:+1);
F=sqrt(3).*(2.*(X.^2+Y.^2)-1);
Thanking You! Here is a particular code. Can anyone please help me in taking the analytical (partial) derivative of the function ‘F’ along X (i.e., w.r.t. X) along Y (i.e., w.r.t. Y) and along the diagonal (i.e., w.r.t. X plus w.r.t. Y) using matlab command.
[X, Y]=meshgrid(-1:2/511:+1, -1:2/511:+1);
F=sqrt(3).*(2.*(X.^2+Y.^2)-1);
Thanking You! differential equations MATLAB Answers — New Questions
Different dilution effect on the kinetics of a time course
Hi to everyone!
To simplify the explanation and the problem, I simulated the kinetics of an irreversible first-order reaction, A -> B. I implemented it in two independent compartments, R and P. I simulated the effect of a dilution in R by doubling at t= 0,1 the R volume. I programmed in P that, at t = 0.1, the instantaneous concentration of A and B would be reduced by half. I am sending an attach with the implementation of these simulations in the Simbiology interface.
When the simulations of the two compartments are plotted, it can be seen that the responses are not equal. That is, from t = 0.1 s, the reaction follow an exponential function in R with half of the initial amplitude and half of the initial value of k1. That is, the relaxation time is doubled. Meanwhile, in P, from t = 0.1, the reaction follows exponential kinetics with half the amplitude value but maintaining the initial value of k = 10. Without a doubt, the correct simulation is the latter (compartment P) where only the effect is observed in the amplitude and not in the relaxation time. Could you tell me what the error is that makes these kinetics that should be equal not be?
Thank you in advance!
Luis B.Hi to everyone!
To simplify the explanation and the problem, I simulated the kinetics of an irreversible first-order reaction, A -> B. I implemented it in two independent compartments, R and P. I simulated the effect of a dilution in R by doubling at t= 0,1 the R volume. I programmed in P that, at t = 0.1, the instantaneous concentration of A and B would be reduced by half. I am sending an attach with the implementation of these simulations in the Simbiology interface.
When the simulations of the two compartments are plotted, it can be seen that the responses are not equal. That is, from t = 0.1 s, the reaction follow an exponential function in R with half of the initial amplitude and half of the initial value of k1. That is, the relaxation time is doubled. Meanwhile, in P, from t = 0.1, the reaction follows exponential kinetics with half the amplitude value but maintaining the initial value of k = 10. Without a doubt, the correct simulation is the latter (compartment P) where only the effect is observed in the amplitude and not in the relaxation time. Could you tell me what the error is that makes these kinetics that should be equal not be?
Thank you in advance!
Luis B. Hi to everyone!
To simplify the explanation and the problem, I simulated the kinetics of an irreversible first-order reaction, A -> B. I implemented it in two independent compartments, R and P. I simulated the effect of a dilution in R by doubling at t= 0,1 the R volume. I programmed in P that, at t = 0.1, the instantaneous concentration of A and B would be reduced by half. I am sending an attach with the implementation of these simulations in the Simbiology interface.
When the simulations of the two compartments are plotted, it can be seen that the responses are not equal. That is, from t = 0.1 s, the reaction follow an exponential function in R with half of the initial amplitude and half of the initial value of k1. That is, the relaxation time is doubled. Meanwhile, in P, from t = 0.1, the reaction follows exponential kinetics with half the amplitude value but maintaining the initial value of k = 10. Without a doubt, the correct simulation is the latter (compartment P) where only the effect is observed in the amplitude and not in the relaxation time. Could you tell me what the error is that makes these kinetics that should be equal not be?
Thank you in advance!
Luis B. simbiolog MATLAB Answers — New Questions
Computation time significantly differs for 2D, 3D array indexing when solving the same problem. Best approach to address performance?
I wrote a simple code that calculates the covariance of images along different directions and lag spacings and returns a 2D map of covariance values varying by lags(h1,h2). The original program I wrote accepts only 2D inputs:
function [Correlogram] = ExhaustiveCovarianceFunction(X,lags)
[ny,nx,~]=size(X);
Covariance=NaN([2*lags+1 2*lags+1]);
Correlogram=NaN([2*lags+1 2*lags+1]);
for hy=-lags:lags
for hx=-lags:lags
sumprod=0;
sum1=0;
sum2=0;
countpairs=0;
for j=1:ny
for i=1:nx
if hy+j<=0 || hy+j>ny || hx+i<=0 || hx+i>nx
countpairs=countpairs;
continue
else
sumprod=X(j,i)*X(j+hy,i+hx) + sumprod;
sum1=X(j,i) + sum1;
sum2=X(j+hy,i+hx) + sum2;
countpairs=countpairs+1;
end
end
end
sumprod=sumprod/(countpairs);
sum1=sum1/(countpairs);
sum2=sum2/(countpairs);
Covariance(hy+lags+1,hx+lags+1)=sumprod – sum1*sum2;
%Standardize covariance values to correlogram
mean1=sum1;
mean2=sum2;
countpairs=0;
sumvar1=0;
sumvar2=0;
for j=1:ny
for i=1:nx
if hy+j<=0 || hy+j>ny || hx+i<=0 || hx+i>nx
continue
else
sumvar1=(X(j,i)-mean1)^2 + sumvar1;
sumvar2=(X(j+hy,i+hx)-mean2)^2 + sumvar2;
countpairs=countpairs+1;
end
end
end
sumvar1=sumvar1/countpairs;
sumvar2=sumvar2/countpairs;
Correlogram(hy+lags+1,hx+lags+1)=Covariance(hy+lags+1,hx+lags+1)/sqrt(sumvar1*sumvar2);
end
end
end
I wanted to extend this code to allow for up to 3D image inputs, but also allow 2D or 1D inputs. Some other changes for optimization were made (dynamically updating bounds, removing if/else statement):
function [Correlogram] = ExhaustiveCovarianceFunction3D(X,lags)
[ny,nx,nz]=size(X);
%lags is now a vector
Covariance=NaN([2*lags(1)+1, 2*lags(2)+1, 2*lags(3)+1]);
Correlogram=NaN([2*lags(1)+1, 2*lags(2)+1, 2*lags(3)+1]);
for hz=-lags(3):lags(3)
for hy=-lags(1):lags(1)
for hx=-lags(2):lags(2)
hvector = [hy hx hz];
if hvector(1)<0
ymin=abs(hvector(1))+1;
ymax=ny;
else
ymin=1;
ymax=ny-hvector(1);
end
if hvector(2)<0
xmin=abs(hvector(2))+1;
xmax=nx;
else
xmin=1;
xmax=nx-hvector(2);
end
if hvector(3)<0
zmin=abs(hvector(3))+1;
zmax=nz;
else
zmin=1;
zmax=nz-hvector(3);
end
sumprod=0;
sum1=0;
sum2=0;
for k=zmin:zmax
for j=ymin:ymax
for i=xmin:xmax
sumprod=X(j,i,k)*X(j+hy,i+hx,k+hz) + sumprod;
sum1=X(j,i,k) + sum1;
sum2=X(j+hy,i+hx,k+hz) + sum2;
end
end
end
countpairs = numel(ymin:ymax)*numel(xmin:xmax)*numel(zmin:zmax);
sumprod=sumprod/(countpairs);
sum1=sum1/(countpairs);
sum2=sum2/(countpairs);
Covariance(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)=sumprod – sum1*sum2;
%Standardize covariance values to correlogram
mean1=sum1;
mean2=sum2;
sumvar1=0;
sumvar2=0;
for k=zmin:zmax
for j=ymin:ymax
for i=xmin:xmax
sumvar1=(X(j,i,k)-mean1)^2 + sumvar1;
sumvar2=(X(j+hy,i+hx,k+hz)-mean2)^2 + sumvar2;
end
end
end
sumvar1=sumvar1/countpairs;
sumvar2=sumvar2/countpairs;
Correlogram(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)=Covariance(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)/sqrt(sumvar1*sumvar2);
end
end
end
end
I first compared these codes for a 2D input image (nz=1) and noticed that my new function runs much slower than the original function:
ExhaustiveCovarianceFunction(testslice,25): Elapsed time is 0.057659 seconds.
ExhaustiveCovarianceFunction3D(testslice,[25,25,0]): Elapsed time is 19.251866 seconds.
After some testing, this led me to realize that indexing a 3D array is much slower than a 2D array in MATLAB, and that this has something to do with how memory is accessed for higher-dimensional arrays. I found out that, if I added a third dimension to the original ExhaustiveCovarianceFunction with index 1 that never changed (eg, X(j,i,1), with no other changes, the code slowed down significantly:
2D array index X(j,i): Elapsed time is 0.059815 seconds.
3D array index X(j,i,1): Elapsed time is 18.849217 seconds.
The idea that we cannot work with higher-dimensional arrays in MATLAB if we want to have optimal performance led me to an approach where, in my new function, I convert the 2D and 3D arrays to a 1D array and map the nD array indices to 1D:
function index1D = convert3Dto1D_index(j, i, k, ny, nx)
index1D = j + (i – 1) * ny + (k – 1) * ny * nx;
end
function [Correlogram] = ExhaustiveCovarianceFunction3D(Xinput,lags)
X = flatten3D(Xinput);
[ny,nx,nz]=size(Xinput);
%lags is now a vector
Covariance=NaN([2*lags(1)+1, 2*lags(2)+1, 2*lags(3)+1]);
Correlogram=NaN([2*lags(1)+1, 2*lags(2)+1, 2*lags(3)+1]);
for hz=-lags(3):lags(3)
for hy=-lags(1):lags(1)
for hx=-lags(2):lags(2)
hvector = [hy hx hz];
if hvector(1)<0
ymin=abs(hvector(1))+1;
ymax=ny;
else
ymin=1;
ymax=ny-hvector(1);
end
if hvector(2)<0
xmin=abs(hvector(2))+1;
xmax=nx;
else
xmin=1;
xmax=nx-hvector(2);
end
if hvector(3)<0
zmin=abs(hvector(3))+1;
zmax=nz;
else
zmin=1;
zmax=nz-hvector(3);
end
sumprod=0;
sum1=0;
sum2=0;
countpairs=0;
for k=zmin:zmax
for j=ymin:ymax
for i=xmin:xmax
sumprod=X(convert3Dto1D_index(j, i, k, ny, nx))*X(convert3Dto1D_index(j+hy, i+hx, k+hz, ny, nx)) + sumprod;
sum1=X(convert3Dto1D_index(j, i, k, ny, nx)) + sum1;
sum2=X(convert3Dto1D_index(j+hy, i+hx, k+hz, ny, nx)) + sum2;
countpairs=countpairs+1;
end
end
end
countpairs = numel(ymin:ymax)*numel(xmin:xmax)*numel(zmin:zmax);
sumprod=sumprod/(countpairs);
sum1=sum1/(countpairs);
sum2=sum2/(countpairs);
Covariance(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)=sumprod – sum1*sum2;
%Standardize covariance values to correlogram
mean1=sum1;
mean2=sum2;
sumvar1=0;
sumvar2=0;
for k=zmin:zmax
for j=ymin:ymax
for i=xmin:xmax
sumvar1=(X(convert3Dto1D_index(j, i, k, ny, nx))-mean1)^2 + sumvar1;
sumvar2=(X(convert3Dto1D_index(j+hy, i+hx, k+hz, ny, nx))-mean2)^2 + sumvar2;
end
end
end
sumvar1=sumvar1/countpairs;
sumvar2=sumvar2/countpairs;
Correlogram(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)=Covariance(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)/sqrt(sumvar1*sumvar2);
end
end
end
end
This approach has better performance, but is still slower than the original 2D code:
2D: Elapsed time is 0.163243 seconds.
3D, 3D index: Elapsed time is 18.336108 seconds.
3D, 1D index: Elapsed time is 0.431890 seconds.
The optimized code with 1D array indexing is still about 3x slower. Perhaps calling convert3Dto1D_index(j, i, k, ny, nx) every time the image index is called is leading to this expense.These computational concerns are important for larger images (eg, 256x256x128) and for higher-order statistics that will be developed.
Is there a smarter approach to addressing this problem? I cannot figure out how to speed up this 3D code any more. Ideally, I seek to make the 3D/general code to have comparable speeds to the 2D "hard-coded" problem when a 2D image is input. If this is not possible, separate subroutines for 2D and 3D images is likely my best bet.I wrote a simple code that calculates the covariance of images along different directions and lag spacings and returns a 2D map of covariance values varying by lags(h1,h2). The original program I wrote accepts only 2D inputs:
function [Correlogram] = ExhaustiveCovarianceFunction(X,lags)
[ny,nx,~]=size(X);
Covariance=NaN([2*lags+1 2*lags+1]);
Correlogram=NaN([2*lags+1 2*lags+1]);
for hy=-lags:lags
for hx=-lags:lags
sumprod=0;
sum1=0;
sum2=0;
countpairs=0;
for j=1:ny
for i=1:nx
if hy+j<=0 || hy+j>ny || hx+i<=0 || hx+i>nx
countpairs=countpairs;
continue
else
sumprod=X(j,i)*X(j+hy,i+hx) + sumprod;
sum1=X(j,i) + sum1;
sum2=X(j+hy,i+hx) + sum2;
countpairs=countpairs+1;
end
end
end
sumprod=sumprod/(countpairs);
sum1=sum1/(countpairs);
sum2=sum2/(countpairs);
Covariance(hy+lags+1,hx+lags+1)=sumprod – sum1*sum2;
%Standardize covariance values to correlogram
mean1=sum1;
mean2=sum2;
countpairs=0;
sumvar1=0;
sumvar2=0;
for j=1:ny
for i=1:nx
if hy+j<=0 || hy+j>ny || hx+i<=0 || hx+i>nx
continue
else
sumvar1=(X(j,i)-mean1)^2 + sumvar1;
sumvar2=(X(j+hy,i+hx)-mean2)^2 + sumvar2;
countpairs=countpairs+1;
end
end
end
sumvar1=sumvar1/countpairs;
sumvar2=sumvar2/countpairs;
Correlogram(hy+lags+1,hx+lags+1)=Covariance(hy+lags+1,hx+lags+1)/sqrt(sumvar1*sumvar2);
end
end
end
I wanted to extend this code to allow for up to 3D image inputs, but also allow 2D or 1D inputs. Some other changes for optimization were made (dynamically updating bounds, removing if/else statement):
function [Correlogram] = ExhaustiveCovarianceFunction3D(X,lags)
[ny,nx,nz]=size(X);
%lags is now a vector
Covariance=NaN([2*lags(1)+1, 2*lags(2)+1, 2*lags(3)+1]);
Correlogram=NaN([2*lags(1)+1, 2*lags(2)+1, 2*lags(3)+1]);
for hz=-lags(3):lags(3)
for hy=-lags(1):lags(1)
for hx=-lags(2):lags(2)
hvector = [hy hx hz];
if hvector(1)<0
ymin=abs(hvector(1))+1;
ymax=ny;
else
ymin=1;
ymax=ny-hvector(1);
end
if hvector(2)<0
xmin=abs(hvector(2))+1;
xmax=nx;
else
xmin=1;
xmax=nx-hvector(2);
end
if hvector(3)<0
zmin=abs(hvector(3))+1;
zmax=nz;
else
zmin=1;
zmax=nz-hvector(3);
end
sumprod=0;
sum1=0;
sum2=0;
for k=zmin:zmax
for j=ymin:ymax
for i=xmin:xmax
sumprod=X(j,i,k)*X(j+hy,i+hx,k+hz) + sumprod;
sum1=X(j,i,k) + sum1;
sum2=X(j+hy,i+hx,k+hz) + sum2;
end
end
end
countpairs = numel(ymin:ymax)*numel(xmin:xmax)*numel(zmin:zmax);
sumprod=sumprod/(countpairs);
sum1=sum1/(countpairs);
sum2=sum2/(countpairs);
Covariance(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)=sumprod – sum1*sum2;
%Standardize covariance values to correlogram
mean1=sum1;
mean2=sum2;
sumvar1=0;
sumvar2=0;
for k=zmin:zmax
for j=ymin:ymax
for i=xmin:xmax
sumvar1=(X(j,i,k)-mean1)^2 + sumvar1;
sumvar2=(X(j+hy,i+hx,k+hz)-mean2)^2 + sumvar2;
end
end
end
sumvar1=sumvar1/countpairs;
sumvar2=sumvar2/countpairs;
Correlogram(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)=Covariance(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)/sqrt(sumvar1*sumvar2);
end
end
end
end
I first compared these codes for a 2D input image (nz=1) and noticed that my new function runs much slower than the original function:
ExhaustiveCovarianceFunction(testslice,25): Elapsed time is 0.057659 seconds.
ExhaustiveCovarianceFunction3D(testslice,[25,25,0]): Elapsed time is 19.251866 seconds.
After some testing, this led me to realize that indexing a 3D array is much slower than a 2D array in MATLAB, and that this has something to do with how memory is accessed for higher-dimensional arrays. I found out that, if I added a third dimension to the original ExhaustiveCovarianceFunction with index 1 that never changed (eg, X(j,i,1), with no other changes, the code slowed down significantly:
2D array index X(j,i): Elapsed time is 0.059815 seconds.
3D array index X(j,i,1): Elapsed time is 18.849217 seconds.
The idea that we cannot work with higher-dimensional arrays in MATLAB if we want to have optimal performance led me to an approach where, in my new function, I convert the 2D and 3D arrays to a 1D array and map the nD array indices to 1D:
function index1D = convert3Dto1D_index(j, i, k, ny, nx)
index1D = j + (i – 1) * ny + (k – 1) * ny * nx;
end
function [Correlogram] = ExhaustiveCovarianceFunction3D(Xinput,lags)
X = flatten3D(Xinput);
[ny,nx,nz]=size(Xinput);
%lags is now a vector
Covariance=NaN([2*lags(1)+1, 2*lags(2)+1, 2*lags(3)+1]);
Correlogram=NaN([2*lags(1)+1, 2*lags(2)+1, 2*lags(3)+1]);
for hz=-lags(3):lags(3)
for hy=-lags(1):lags(1)
for hx=-lags(2):lags(2)
hvector = [hy hx hz];
if hvector(1)<0
ymin=abs(hvector(1))+1;
ymax=ny;
else
ymin=1;
ymax=ny-hvector(1);
end
if hvector(2)<0
xmin=abs(hvector(2))+1;
xmax=nx;
else
xmin=1;
xmax=nx-hvector(2);
end
if hvector(3)<0
zmin=abs(hvector(3))+1;
zmax=nz;
else
zmin=1;
zmax=nz-hvector(3);
end
sumprod=0;
sum1=0;
sum2=0;
countpairs=0;
for k=zmin:zmax
for j=ymin:ymax
for i=xmin:xmax
sumprod=X(convert3Dto1D_index(j, i, k, ny, nx))*X(convert3Dto1D_index(j+hy, i+hx, k+hz, ny, nx)) + sumprod;
sum1=X(convert3Dto1D_index(j, i, k, ny, nx)) + sum1;
sum2=X(convert3Dto1D_index(j+hy, i+hx, k+hz, ny, nx)) + sum2;
countpairs=countpairs+1;
end
end
end
countpairs = numel(ymin:ymax)*numel(xmin:xmax)*numel(zmin:zmax);
sumprod=sumprod/(countpairs);
sum1=sum1/(countpairs);
sum2=sum2/(countpairs);
Covariance(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)=sumprod – sum1*sum2;
%Standardize covariance values to correlogram
mean1=sum1;
mean2=sum2;
sumvar1=0;
sumvar2=0;
for k=zmin:zmax
for j=ymin:ymax
for i=xmin:xmax
sumvar1=(X(convert3Dto1D_index(j, i, k, ny, nx))-mean1)^2 + sumvar1;
sumvar2=(X(convert3Dto1D_index(j+hy, i+hx, k+hz, ny, nx))-mean2)^2 + sumvar2;
end
end
end
sumvar1=sumvar1/countpairs;
sumvar2=sumvar2/countpairs;
Correlogram(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)=Covariance(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)/sqrt(sumvar1*sumvar2);
end
end
end
end
This approach has better performance, but is still slower than the original 2D code:
2D: Elapsed time is 0.163243 seconds.
3D, 3D index: Elapsed time is 18.336108 seconds.
3D, 1D index: Elapsed time is 0.431890 seconds.
The optimized code with 1D array indexing is still about 3x slower. Perhaps calling convert3Dto1D_index(j, i, k, ny, nx) every time the image index is called is leading to this expense.These computational concerns are important for larger images (eg, 256x256x128) and for higher-order statistics that will be developed.
Is there a smarter approach to addressing this problem? I cannot figure out how to speed up this 3D code any more. Ideally, I seek to make the 3D/general code to have comparable speeds to the 2D "hard-coded" problem when a 2D image is input. If this is not possible, separate subroutines for 2D and 3D images is likely my best bet. I wrote a simple code that calculates the covariance of images along different directions and lag spacings and returns a 2D map of covariance values varying by lags(h1,h2). The original program I wrote accepts only 2D inputs:
function [Correlogram] = ExhaustiveCovarianceFunction(X,lags)
[ny,nx,~]=size(X);
Covariance=NaN([2*lags+1 2*lags+1]);
Correlogram=NaN([2*lags+1 2*lags+1]);
for hy=-lags:lags
for hx=-lags:lags
sumprod=0;
sum1=0;
sum2=0;
countpairs=0;
for j=1:ny
for i=1:nx
if hy+j<=0 || hy+j>ny || hx+i<=0 || hx+i>nx
countpairs=countpairs;
continue
else
sumprod=X(j,i)*X(j+hy,i+hx) + sumprod;
sum1=X(j,i) + sum1;
sum2=X(j+hy,i+hx) + sum2;
countpairs=countpairs+1;
end
end
end
sumprod=sumprod/(countpairs);
sum1=sum1/(countpairs);
sum2=sum2/(countpairs);
Covariance(hy+lags+1,hx+lags+1)=sumprod – sum1*sum2;
%Standardize covariance values to correlogram
mean1=sum1;
mean2=sum2;
countpairs=0;
sumvar1=0;
sumvar2=0;
for j=1:ny
for i=1:nx
if hy+j<=0 || hy+j>ny || hx+i<=0 || hx+i>nx
continue
else
sumvar1=(X(j,i)-mean1)^2 + sumvar1;
sumvar2=(X(j+hy,i+hx)-mean2)^2 + sumvar2;
countpairs=countpairs+1;
end
end
end
sumvar1=sumvar1/countpairs;
sumvar2=sumvar2/countpairs;
Correlogram(hy+lags+1,hx+lags+1)=Covariance(hy+lags+1,hx+lags+1)/sqrt(sumvar1*sumvar2);
end
end
end
I wanted to extend this code to allow for up to 3D image inputs, but also allow 2D or 1D inputs. Some other changes for optimization were made (dynamically updating bounds, removing if/else statement):
function [Correlogram] = ExhaustiveCovarianceFunction3D(X,lags)
[ny,nx,nz]=size(X);
%lags is now a vector
Covariance=NaN([2*lags(1)+1, 2*lags(2)+1, 2*lags(3)+1]);
Correlogram=NaN([2*lags(1)+1, 2*lags(2)+1, 2*lags(3)+1]);
for hz=-lags(3):lags(3)
for hy=-lags(1):lags(1)
for hx=-lags(2):lags(2)
hvector = [hy hx hz];
if hvector(1)<0
ymin=abs(hvector(1))+1;
ymax=ny;
else
ymin=1;
ymax=ny-hvector(1);
end
if hvector(2)<0
xmin=abs(hvector(2))+1;
xmax=nx;
else
xmin=1;
xmax=nx-hvector(2);
end
if hvector(3)<0
zmin=abs(hvector(3))+1;
zmax=nz;
else
zmin=1;
zmax=nz-hvector(3);
end
sumprod=0;
sum1=0;
sum2=0;
for k=zmin:zmax
for j=ymin:ymax
for i=xmin:xmax
sumprod=X(j,i,k)*X(j+hy,i+hx,k+hz) + sumprod;
sum1=X(j,i,k) + sum1;
sum2=X(j+hy,i+hx,k+hz) + sum2;
end
end
end
countpairs = numel(ymin:ymax)*numel(xmin:xmax)*numel(zmin:zmax);
sumprod=sumprod/(countpairs);
sum1=sum1/(countpairs);
sum2=sum2/(countpairs);
Covariance(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)=sumprod – sum1*sum2;
%Standardize covariance values to correlogram
mean1=sum1;
mean2=sum2;
sumvar1=0;
sumvar2=0;
for k=zmin:zmax
for j=ymin:ymax
for i=xmin:xmax
sumvar1=(X(j,i,k)-mean1)^2 + sumvar1;
sumvar2=(X(j+hy,i+hx,k+hz)-mean2)^2 + sumvar2;
end
end
end
sumvar1=sumvar1/countpairs;
sumvar2=sumvar2/countpairs;
Correlogram(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)=Covariance(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)/sqrt(sumvar1*sumvar2);
end
end
end
end
I first compared these codes for a 2D input image (nz=1) and noticed that my new function runs much slower than the original function:
ExhaustiveCovarianceFunction(testslice,25): Elapsed time is 0.057659 seconds.
ExhaustiveCovarianceFunction3D(testslice,[25,25,0]): Elapsed time is 19.251866 seconds.
After some testing, this led me to realize that indexing a 3D array is much slower than a 2D array in MATLAB, and that this has something to do with how memory is accessed for higher-dimensional arrays. I found out that, if I added a third dimension to the original ExhaustiveCovarianceFunction with index 1 that never changed (eg, X(j,i,1), with no other changes, the code slowed down significantly:
2D array index X(j,i): Elapsed time is 0.059815 seconds.
3D array index X(j,i,1): Elapsed time is 18.849217 seconds.
The idea that we cannot work with higher-dimensional arrays in MATLAB if we want to have optimal performance led me to an approach where, in my new function, I convert the 2D and 3D arrays to a 1D array and map the nD array indices to 1D:
function index1D = convert3Dto1D_index(j, i, k, ny, nx)
index1D = j + (i – 1) * ny + (k – 1) * ny * nx;
end
function [Correlogram] = ExhaustiveCovarianceFunction3D(Xinput,lags)
X = flatten3D(Xinput);
[ny,nx,nz]=size(Xinput);
%lags is now a vector
Covariance=NaN([2*lags(1)+1, 2*lags(2)+1, 2*lags(3)+1]);
Correlogram=NaN([2*lags(1)+1, 2*lags(2)+1, 2*lags(3)+1]);
for hz=-lags(3):lags(3)
for hy=-lags(1):lags(1)
for hx=-lags(2):lags(2)
hvector = [hy hx hz];
if hvector(1)<0
ymin=abs(hvector(1))+1;
ymax=ny;
else
ymin=1;
ymax=ny-hvector(1);
end
if hvector(2)<0
xmin=abs(hvector(2))+1;
xmax=nx;
else
xmin=1;
xmax=nx-hvector(2);
end
if hvector(3)<0
zmin=abs(hvector(3))+1;
zmax=nz;
else
zmin=1;
zmax=nz-hvector(3);
end
sumprod=0;
sum1=0;
sum2=0;
countpairs=0;
for k=zmin:zmax
for j=ymin:ymax
for i=xmin:xmax
sumprod=X(convert3Dto1D_index(j, i, k, ny, nx))*X(convert3Dto1D_index(j+hy, i+hx, k+hz, ny, nx)) + sumprod;
sum1=X(convert3Dto1D_index(j, i, k, ny, nx)) + sum1;
sum2=X(convert3Dto1D_index(j+hy, i+hx, k+hz, ny, nx)) + sum2;
countpairs=countpairs+1;
end
end
end
countpairs = numel(ymin:ymax)*numel(xmin:xmax)*numel(zmin:zmax);
sumprod=sumprod/(countpairs);
sum1=sum1/(countpairs);
sum2=sum2/(countpairs);
Covariance(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)=sumprod – sum1*sum2;
%Standardize covariance values to correlogram
mean1=sum1;
mean2=sum2;
sumvar1=0;
sumvar2=0;
for k=zmin:zmax
for j=ymin:ymax
for i=xmin:xmax
sumvar1=(X(convert3Dto1D_index(j, i, k, ny, nx))-mean1)^2 + sumvar1;
sumvar2=(X(convert3Dto1D_index(j+hy, i+hx, k+hz, ny, nx))-mean2)^2 + sumvar2;
end
end
end
sumvar1=sumvar1/countpairs;
sumvar2=sumvar2/countpairs;
Correlogram(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)=Covariance(hy+lags(1)+1,hx+lags(2)+1, hz+lags(3)+1)/sqrt(sumvar1*sumvar2);
end
end
end
end
This approach has better performance, but is still slower than the original 2D code:
2D: Elapsed time is 0.163243 seconds.
3D, 3D index: Elapsed time is 18.336108 seconds.
3D, 1D index: Elapsed time is 0.431890 seconds.
The optimized code with 1D array indexing is still about 3x slower. Perhaps calling convert3Dto1D_index(j, i, k, ny, nx) every time the image index is called is leading to this expense.These computational concerns are important for larger images (eg, 256x256x128) and for higher-order statistics that will be developed.
Is there a smarter approach to addressing this problem? I cannot figure out how to speed up this 3D code any more. Ideally, I seek to make the 3D/general code to have comparable speeds to the 2D "hard-coded" problem when a 2D image is input. If this is not possible, separate subroutines for 2D and 3D images is likely my best bet. computation time, performance, time complexity, bigo, arrays, 2d, 3d, algorithm optimization MATLAB Answers — New Questions
SD from k-fold validation classification learner
I am dealing with a reviewer that ask for the standard deviation obtained in the k-fold validation LDA algorithm obtained from the classification learner app.
How can I do it?I am dealing with a reviewer that ask for the standard deviation obtained in the k-fold validation LDA algorithm obtained from the classification learner app.
How can I do it? I am dealing with a reviewer that ask for the standard deviation obtained in the k-fold validation LDA algorithm obtained from the classification learner app.
How can I do it? machine learning, app classification, k-fold, classification MATLAB Answers — New Questions
How do I reset MATLAB to its launched state?
Is it possible to "reset" MATLAB? Sometimes I want to "restore" MATLAB to the way it is when it is launched (not the way it was when it is installed). Closing all the figures, resetting the path and clearing variables is relatively easy, but not as easy as:
close all; clear all; path(pathdef); clc;
You need extra flags since the "all" flag is not really all (e.g., a figure might be hidden or mfiles files might be locked).
Resetting non-persistent "default" values is harder. For example, if at some point the "DefaultFigurePosition" is modified:
set(0, ‘DefaultFigurePosition’, [100, 100, 100, 100])
that change needs to be identified and reversed.
The list of things to get a full reset seems long to me. There are also issues about do I want to restore MATLAB to the way it was when it started or the way it will be the next time it starts. At this point I would be happy with either (or a mix).Is it possible to "reset" MATLAB? Sometimes I want to "restore" MATLAB to the way it is when it is launched (not the way it was when it is installed). Closing all the figures, resetting the path and clearing variables is relatively easy, but not as easy as:
close all; clear all; path(pathdef); clc;
You need extra flags since the "all" flag is not really all (e.g., a figure might be hidden or mfiles files might be locked).
Resetting non-persistent "default" values is harder. For example, if at some point the "DefaultFigurePosition" is modified:
set(0, ‘DefaultFigurePosition’, [100, 100, 100, 100])
that change needs to be identified and reversed.
The list of things to get a full reset seems long to me. There are also issues about do I want to restore MATLAB to the way it was when it started or the way it will be the next time it starts. At this point I would be happy with either (or a mix). Is it possible to "reset" MATLAB? Sometimes I want to "restore" MATLAB to the way it is when it is launched (not the way it was when it is installed). Closing all the figures, resetting the path and clearing variables is relatively easy, but not as easy as:
close all; clear all; path(pathdef); clc;
You need extra flags since the "all" flag is not really all (e.g., a figure might be hidden or mfiles files might be locked).
Resetting non-persistent "default" values is harder. For example, if at some point the "DefaultFigurePosition" is modified:
set(0, ‘DefaultFigurePosition’, [100, 100, 100, 100])
that change needs to be identified and reversed.
The list of things to get a full reset seems long to me. There are also issues about do I want to restore MATLAB to the way it was when it started or the way it will be the next time it starts. At this point I would be happy with either (or a mix). startup, function MATLAB Answers — New Questions
Invalid text character. Check for unsupported symbol, invisible character, or pasting of non-ASCII characters.
I really don’t know what is the reason for this error. PLease help!
theta_dd(i)= (kP*r(i) +kD*r_dot(i) -(m*g*l+kP)*sin(theta(i)) -kD*theta_dot(i))/M;I really don’t know what is the reason for this error. PLease help!
theta_dd(i)= (kP*r(i) +kD*r_dot(i) -(m*g*l+kP)*sin(theta(i)) -kD*theta_dot(i))/M; I really don’t know what is the reason for this error. PLease help!
theta_dd(i)= (kP*r(i) +kD*r_dot(i) -(m*g*l+kP)*sin(theta(i)) -kD*theta_dot(i))/M; invalid text character. check for unsupported symbol, invisible character, or pasting of non-ascii characters. MATLAB Answers — New Questions
Simulink Real time explorer
Why i dont get the same simulink blocs and interface when i run slrtExplorer in matlab R2020b as my Friend despite that we have the same version of matlabWhy i dont get the same simulink blocs and interface when i run slrtExplorer in matlab R2020b as my Friend despite that we have the same version of matlab Why i dont get the same simulink blocs and interface when i run slrtExplorer in matlab R2020b as my Friend despite that we have the same version of matlab transferred MATLAB Answers — New Questions
Using CZI files within the Medical Image Labeler
I have some CZI files I want to use within the medical image labeler app, but this not currently an accepted file format. What would be the best way for me to convert them into a format the app can read?I have some CZI files I want to use within the medical image labeler app, but this not currently an accepted file format. What would be the best way for me to convert them into a format the app can read? I have some CZI files I want to use within the medical image labeler app, but this not currently an accepted file format. What would be the best way for me to convert them into a format the app can read? medical image labeler MATLAB Answers — New Questions
Matab is very slow in processing figures: might it be caused by NVidia Optimus?
Hi all,
I have a laptop with the following configuration:
CPU: i7-11850H
RAM: 32GB
GPUs: Intel UHD graphics and NVIDIA RTX A2000
I notice that my laptos is pretty slow especially when managing figures. Indeed, by running bench command, the relative speed is 5.78 (this is the output of bench command 0.8408 0.3923 0.3292 0.6592 6.4034 7.0999) and my system lag hugely with respect the reference machines in 2-D and 3-D performance. When running bench command, the CPU usage peaked 18%. From this data, I believe that my system mostly run with Intel graphics rather on on my NVidia. Is that possible to verify which GPU card is running when Matlab is processing?
Thanks for your help.Hi all,
I have a laptop with the following configuration:
CPU: i7-11850H
RAM: 32GB
GPUs: Intel UHD graphics and NVIDIA RTX A2000
I notice that my laptos is pretty slow especially when managing figures. Indeed, by running bench command, the relative speed is 5.78 (this is the output of bench command 0.8408 0.3923 0.3292 0.6592 6.4034 7.0999) and my system lag hugely with respect the reference machines in 2-D and 3-D performance. When running bench command, the CPU usage peaked 18%. From this data, I believe that my system mostly run with Intel graphics rather on on my NVidia. Is that possible to verify which GPU card is running when Matlab is processing?
Thanks for your help. Hi all,
I have a laptop with the following configuration:
CPU: i7-11850H
RAM: 32GB
GPUs: Intel UHD graphics and NVIDIA RTX A2000
I notice that my laptos is pretty slow especially when managing figures. Indeed, by running bench command, the relative speed is 5.78 (this is the output of bench command 0.8408 0.3923 0.3292 0.6592 6.4034 7.0999) and my system lag hugely with respect the reference machines in 2-D and 3-D performance. When running bench command, the CPU usage peaked 18%. From this data, I believe that my system mostly run with Intel graphics rather on on my NVidia. Is that possible to verify which GPU card is running when Matlab is processing?
Thanks for your help. matlab MATLAB Answers — New Questions
How to find steady-error value from the response graph? is there any command to find the steady state error from the response graph?
G(s)=5/s^2+2s+25G(s)=5/s^2+2s+25 G(s)=5/s^2+2s+25 steady-state error, control, theory MATLAB Answers — New Questions
Axis exponent causing all text in the figure to render as curves instead of text in svg
I’m using the saveas function to export a figure as an svg file. I have set the renderer to be painters but occasionally the output of text is rendered as curves in the svg file.
Everything works fine except when using greek letters in axis labels (which I have avoided) or when the axis label contains exponents automatically by MATLAB. If I delete the " x 10^5 " part manually in the figure window or in the code I include ax = gca; ax.YAxis.Exponent = 0, then the saveas works fine exporting an svg file with text rendered as text. However, this is still a hassle and I’m hoping it can be fixed.
I’m using R2024a.I’m using the saveas function to export a figure as an svg file. I have set the renderer to be painters but occasionally the output of text is rendered as curves in the svg file.
Everything works fine except when using greek letters in axis labels (which I have avoided) or when the axis label contains exponents automatically by MATLAB. If I delete the " x 10^5 " part manually in the figure window or in the code I include ax = gca; ax.YAxis.Exponent = 0, then the saveas works fine exporting an svg file with text rendered as text. However, this is still a hassle and I’m hoping it can be fixed.
I’m using R2024a. I’m using the saveas function to export a figure as an svg file. I have set the renderer to be painters but occasionally the output of text is rendered as curves in the svg file.
Everything works fine except when using greek letters in axis labels (which I have avoided) or when the axis label contains exponents automatically by MATLAB. If I delete the " x 10^5 " part manually in the figure window or in the code I include ax = gca; ax.YAxis.Exponent = 0, then the saveas works fine exporting an svg file with text rendered as text. However, this is still a hassle and I’m hoping it can be fixed.
I’m using R2024a. svg, vector graphics, curves, axis labels MATLAB Answers — New Questions
Why does the MathWorks Service Host create several files on my machine?
Why does the MathWorks Service Host create several files on my machine?Why does the MathWorks Service Host create several files on my machine? Why does the MathWorks Service Host create several files on my machine? MATLAB Answers — New Questions
Why does MATLAB R2021b or newer create a large directory of data for each user in ~/.MathWorks, %localappdata%MathWorks, or ~/Library/Application Support/MathWorks?
Why does MATLAB R2021b or newer create a large directory of data for each user in ~/.MathWorks, %localappdata%MathWorks, or ~/Library/Application Support/MathWorks?Why does MATLAB R2021b or newer create a large directory of data for each user in ~/.MathWorks, %localappdata%MathWorks, or ~/Library/Application Support/MathWorks? Why does MATLAB R2021b or newer create a large directory of data for each user in ~/.MathWorks, %localappdata%MathWorks, or ~/Library/Application Support/MathWorks? MATLAB Answers — New Questions
Simulink communication with a second, real time process on the same Windows PC
For a non-Simulink real time process running on a Windows PC is UDP the best way to communicate with Simulink running on the same PC? Is Simulink Desktop Real-Time the best product for this?For a non-Simulink real time process running on a Windows PC is UDP the best way to communicate with Simulink running on the same PC? Is Simulink Desktop Real-Time the best product for this? For a non-Simulink real time process running on a Windows PC is UDP the best way to communicate with Simulink running on the same PC? Is Simulink Desktop Real-Time the best product for this? udp, simulink, windows pc, separate process MATLAB Answers — New Questions
Why is the MathWorks Service Host causing issues with my cluster and/or HPC?
Why is the MathWorks Service Host causing issues with my cluster and/or HPC?Why is the MathWorks Service Host causing issues with my cluster and/or HPC? Why is the MathWorks Service Host causing issues with my cluster and/or HPC? MATLAB Answers — New Questions
Deep learning using trainnet for resnet18 : old trainnetwork –> new trainnet
Hi,
I copied a matlab example for semantic image segmentation using MATLAB 2022, and the example used ‘trainNetwork’ and ‘deeplabv3plusLayers’ for resnet18, and the results were excellent for my images which have 9 labels (background + 8)
However, now the documentation for trainNetwork recommends moving the training command to be ‘trainnet’, and the documentation for ‘deeplabv3plusLayers’ recommends moving to ‘ deeplabv3plus’. When I follow the provided example (e.g https://www.mathworks.com/help/vision/ug/semantic-segmentation-using-deep-learning.html), my segmentation results are noticibly worse:
…especially for my primary ROIs of interest: ROI1, ROI2, and ROI3.
My program which calls trainnet uses the following options. The function call is also shown here:
options = trainingOptions(‘sgdm’,…
‘InitialLearnRate’,0.1, …
‘Momentum’,0.9,…
‘L2Regularization’,0.0001,…
‘MaxEpochs’,80,…
‘MiniBatchSize’,128,…
‘LearnRateSchedule’,’piecewise’,…
‘Shuffle’,’every-epoch’,…
‘GradientThresholdMethod’,’l2norm’,…
‘GradientThreshold’,0.05, …
‘Plots’,’training-progress’, …
‘VerboseFrequency’,10,…
‘ExecutionEnvironment’,’multi-gpu’,…
‘ValidationData’,dsValid,…
‘ValidationFrequency’,30,…
‘ValidationPatience’,15,…
‘InputDataFormats’, {‘SSCB’});
[ROISegNet,info] = trainnet(dsTrain,network,@(Y,T) modelLoss(Y,T,classWeights),options);
where the modelLoss subroutine is as provided by MATLAB:
function loss = modelLoss(Y,T,classWeights)
weights = dlarray(classWeights,"C");
mask = ~isnan(T);
T(isnan(T)) = 0;
loss = crossentropy(Y,T,weights,Mask=mask,NormalizationFactor="mask-included");
end
As a novice learning how to do this, can anyone offer suggestions on how to handle trainnet such that the results generated are closer to the old version?
Thank you for your help!Hi,
I copied a matlab example for semantic image segmentation using MATLAB 2022, and the example used ‘trainNetwork’ and ‘deeplabv3plusLayers’ for resnet18, and the results were excellent for my images which have 9 labels (background + 8)
However, now the documentation for trainNetwork recommends moving the training command to be ‘trainnet’, and the documentation for ‘deeplabv3plusLayers’ recommends moving to ‘ deeplabv3plus’. When I follow the provided example (e.g https://www.mathworks.com/help/vision/ug/semantic-segmentation-using-deep-learning.html), my segmentation results are noticibly worse:
…especially for my primary ROIs of interest: ROI1, ROI2, and ROI3.
My program which calls trainnet uses the following options. The function call is also shown here:
options = trainingOptions(‘sgdm’,…
‘InitialLearnRate’,0.1, …
‘Momentum’,0.9,…
‘L2Regularization’,0.0001,…
‘MaxEpochs’,80,…
‘MiniBatchSize’,128,…
‘LearnRateSchedule’,’piecewise’,…
‘Shuffle’,’every-epoch’,…
‘GradientThresholdMethod’,’l2norm’,…
‘GradientThreshold’,0.05, …
‘Plots’,’training-progress’, …
‘VerboseFrequency’,10,…
‘ExecutionEnvironment’,’multi-gpu’,…
‘ValidationData’,dsValid,…
‘ValidationFrequency’,30,…
‘ValidationPatience’,15,…
‘InputDataFormats’, {‘SSCB’});
[ROISegNet,info] = trainnet(dsTrain,network,@(Y,T) modelLoss(Y,T,classWeights),options);
where the modelLoss subroutine is as provided by MATLAB:
function loss = modelLoss(Y,T,classWeights)
weights = dlarray(classWeights,"C");
mask = ~isnan(T);
T(isnan(T)) = 0;
loss = crossentropy(Y,T,weights,Mask=mask,NormalizationFactor="mask-included");
end
As a novice learning how to do this, can anyone offer suggestions on how to handle trainnet such that the results generated are closer to the old version?
Thank you for your help! Hi,
I copied a matlab example for semantic image segmentation using MATLAB 2022, and the example used ‘trainNetwork’ and ‘deeplabv3plusLayers’ for resnet18, and the results were excellent for my images which have 9 labels (background + 8)
However, now the documentation for trainNetwork recommends moving the training command to be ‘trainnet’, and the documentation for ‘deeplabv3plusLayers’ recommends moving to ‘ deeplabv3plus’. When I follow the provided example (e.g https://www.mathworks.com/help/vision/ug/semantic-segmentation-using-deep-learning.html), my segmentation results are noticibly worse:
…especially for my primary ROIs of interest: ROI1, ROI2, and ROI3.
My program which calls trainnet uses the following options. The function call is also shown here:
options = trainingOptions(‘sgdm’,…
‘InitialLearnRate’,0.1, …
‘Momentum’,0.9,…
‘L2Regularization’,0.0001,…
‘MaxEpochs’,80,…
‘MiniBatchSize’,128,…
‘LearnRateSchedule’,’piecewise’,…
‘Shuffle’,’every-epoch’,…
‘GradientThresholdMethod’,’l2norm’,…
‘GradientThreshold’,0.05, …
‘Plots’,’training-progress’, …
‘VerboseFrequency’,10,…
‘ExecutionEnvironment’,’multi-gpu’,…
‘ValidationData’,dsValid,…
‘ValidationFrequency’,30,…
‘ValidationPatience’,15,…
‘InputDataFormats’, {‘SSCB’});
[ROISegNet,info] = trainnet(dsTrain,network,@(Y,T) modelLoss(Y,T,classWeights),options);
where the modelLoss subroutine is as provided by MATLAB:
function loss = modelLoss(Y,T,classWeights)
weights = dlarray(classWeights,"C");
mask = ~isnan(T);
T(isnan(T)) = 0;
loss = crossentropy(Y,T,weights,Mask=mask,NormalizationFactor="mask-included");
end
As a novice learning how to do this, can anyone offer suggestions on how to handle trainnet such that the results generated are closer to the old version?
Thank you for your help! deep learning, semantic segmentation, resnet18, trainnet MATLAB Answers — New Questions
Issues setting CoordinateSystem for sim3d.Actor to MATLAB in Simulink; need correct initialization method. Also need third-person view in Simulation 3D Scene Configuration
I’m encountering issues when trying to set the CoordinateSystem property for the sim3d.Actor object in Simulink. According to the documentation, this property should be configurable to use the MATLAB coordinate system, but it results in an error. I need guidance on the correct method to achieve this in the initialization script.
Additionally, I want to configure the Simulation 3D Scene Configuration block so that when selecting my Actor defined in the Simulation 3D Actor block as the Scene view, the view is in third person rather than the default coordinates [0 0 0].
Issue 1: Changing Coordinate System
I am trying to set the CoordinateSystem property for a sim3d.Actor object to use the MATLAB coordinate system. Here is the current initialization script:
fileName = "QuadCopter_Body.stl";
Body = sim3d.Actor(‘ActorName’, ‘Body’, …
‘Mobility’, sim3d.utils.MobilityTypes.Movable, …
‘ActorClassId’, sim3d.utils.SemanticType.Vehicle, …
‘CoordinateSystem’, ‘MATLAB’);
World.add(Body, Actor);
Body.load(fileName, [1 1 1]/100);
Body.Color = [0, 0, 1];
Body.Scale = [10 10 10];
Translation = [0.341 0.286 0.042;
-0.341 0.286 0.042;
0.341 -0.286 0.042;
-0.341 -0.286 0.042];
propellerFileName = "QuadCopter_Propeller.stl";
for propellerIndex = 1:4
actorName = sprintf(‘Propeller%d’, propellerIndex);
Propeller = sim3d.Actor(‘ActorName’,actorName, …
‘Mobility’, sim3d.utils.MobilityTypes.Movable, …
‘ActorClassId’, sim3d.utils.SemanticType.Vehicle);
World.add(Propeller, Actor);
Propeller.load(propellerFileName, [1 1 1]/100);
Propeller.Color = [1, 0, 0];
Propeller.Translation = Translation(propellerIndex, :);
Propeller.Rotation = [0 0 0 ];
Propeller.Scale = [10 10 10];
end
Actor.save("quadcopter.mat")
This is the error:
‘CoordinateSystem’ is not a recognized parameter. For a list of valid name-value pair argument, see the documentation for this function.
Issue 2: Setting Third-Person View
I also want to set the view in the Simulation 3D Scene Configuration block to be in third person when selecting my Actor defined in the Simulation 3D Actor block. Currently, the view defaults to the coordinates [0 0 0]. How can I change this view to a third-person perspective?I’m encountering issues when trying to set the CoordinateSystem property for the sim3d.Actor object in Simulink. According to the documentation, this property should be configurable to use the MATLAB coordinate system, but it results in an error. I need guidance on the correct method to achieve this in the initialization script.
Additionally, I want to configure the Simulation 3D Scene Configuration block so that when selecting my Actor defined in the Simulation 3D Actor block as the Scene view, the view is in third person rather than the default coordinates [0 0 0].
Issue 1: Changing Coordinate System
I am trying to set the CoordinateSystem property for a sim3d.Actor object to use the MATLAB coordinate system. Here is the current initialization script:
fileName = "QuadCopter_Body.stl";
Body = sim3d.Actor(‘ActorName’, ‘Body’, …
‘Mobility’, sim3d.utils.MobilityTypes.Movable, …
‘ActorClassId’, sim3d.utils.SemanticType.Vehicle, …
‘CoordinateSystem’, ‘MATLAB’);
World.add(Body, Actor);
Body.load(fileName, [1 1 1]/100);
Body.Color = [0, 0, 1];
Body.Scale = [10 10 10];
Translation = [0.341 0.286 0.042;
-0.341 0.286 0.042;
0.341 -0.286 0.042;
-0.341 -0.286 0.042];
propellerFileName = "QuadCopter_Propeller.stl";
for propellerIndex = 1:4
actorName = sprintf(‘Propeller%d’, propellerIndex);
Propeller = sim3d.Actor(‘ActorName’,actorName, …
‘Mobility’, sim3d.utils.MobilityTypes.Movable, …
‘ActorClassId’, sim3d.utils.SemanticType.Vehicle);
World.add(Propeller, Actor);
Propeller.load(propellerFileName, [1 1 1]/100);
Propeller.Color = [1, 0, 0];
Propeller.Translation = Translation(propellerIndex, :);
Propeller.Rotation = [0 0 0 ];
Propeller.Scale = [10 10 10];
end
Actor.save("quadcopter.mat")
This is the error:
‘CoordinateSystem’ is not a recognized parameter. For a list of valid name-value pair argument, see the documentation for this function.
Issue 2: Setting Third-Person View
I also want to set the view in the Simulation 3D Scene Configuration block to be in third person when selecting my Actor defined in the Simulation 3D Actor block. Currently, the view defaults to the coordinates [0 0 0]. How can I change this view to a third-person perspective? I’m encountering issues when trying to set the CoordinateSystem property for the sim3d.Actor object in Simulink. According to the documentation, this property should be configurable to use the MATLAB coordinate system, but it results in an error. I need guidance on the correct method to achieve this in the initialization script.
Additionally, I want to configure the Simulation 3D Scene Configuration block so that when selecting my Actor defined in the Simulation 3D Actor block as the Scene view, the view is in third person rather than the default coordinates [0 0 0].
Issue 1: Changing Coordinate System
I am trying to set the CoordinateSystem property for a sim3d.Actor object to use the MATLAB coordinate system. Here is the current initialization script:
fileName = "QuadCopter_Body.stl";
Body = sim3d.Actor(‘ActorName’, ‘Body’, …
‘Mobility’, sim3d.utils.MobilityTypes.Movable, …
‘ActorClassId’, sim3d.utils.SemanticType.Vehicle, …
‘CoordinateSystem’, ‘MATLAB’);
World.add(Body, Actor);
Body.load(fileName, [1 1 1]/100);
Body.Color = [0, 0, 1];
Body.Scale = [10 10 10];
Translation = [0.341 0.286 0.042;
-0.341 0.286 0.042;
0.341 -0.286 0.042;
-0.341 -0.286 0.042];
propellerFileName = "QuadCopter_Propeller.stl";
for propellerIndex = 1:4
actorName = sprintf(‘Propeller%d’, propellerIndex);
Propeller = sim3d.Actor(‘ActorName’,actorName, …
‘Mobility’, sim3d.utils.MobilityTypes.Movable, …
‘ActorClassId’, sim3d.utils.SemanticType.Vehicle);
World.add(Propeller, Actor);
Propeller.load(propellerFileName, [1 1 1]/100);
Propeller.Color = [1, 0, 0];
Propeller.Translation = Translation(propellerIndex, :);
Propeller.Rotation = [0 0 0 ];
Propeller.Scale = [10 10 10];
end
Actor.save("quadcopter.mat")
This is the error:
‘CoordinateSystem’ is not a recognized parameter. For a list of valid name-value pair argument, see the documentation for this function.
Issue 2: Setting Third-Person View
I also want to set the view in the Simulation 3D Scene Configuration block to be in third person when selecting my Actor defined in the Simulation 3D Actor block. Currently, the view defaults to the coordinates [0 0 0]. How can I change this view to a third-person perspective? sim3d, coordinatesystem, simulation3dactor, sceneconfiguration, simulink MATLAB Answers — New Questions
Python Module not found when call the python function using Matlab
I want to call a python function using Matlab. I am working on the NLP project, particularly text recognization. The name of the python file that I want to call using the Matlab is final_output.py. The final_output.py contains a import statement import spacy. This script run well when I run it using Pycharm. I installed all the required library using PyCharm terminal.
However, when I call the same python file from Matlab I received an error,
Error using final_output><module>
Python Error: ModuleNotFoundError: No module named ‘spacy’
Error in <frozen importlib>_call_with_frames_removed (line 228)
Error in <frozen importlib>exec_module (line 850)
Error in <frozen importlib>_load_unlocked (line 680)
Any help will be appreciated.
The Matlab code is as follows
pe = pyenv;
disp(pe);
py.importlib.import_module(‘final_output’)
% Add the directory containing the Python script to the Python path
path_add = fileparts(which(‘final_output.py’));
if count(py.sys.path, path_add) == 0
insert(py.sys.path, int64(0), path_add);
end
% Define model path and text to process
model_path = ‘D:\output\model-best’;
text = ‘Roses are Red’;
% Call the Python function
pyOut = py.final_output.text_recognizer(model_path, text);
% Convert the output to a MATLAB cell array
entity_labels = cell(pyOut);
disp(entity_labels);I want to call a python function using Matlab. I am working on the NLP project, particularly text recognization. The name of the python file that I want to call using the Matlab is final_output.py. The final_output.py contains a import statement import spacy. This script run well when I run it using Pycharm. I installed all the required library using PyCharm terminal.
However, when I call the same python file from Matlab I received an error,
Error using final_output><module>
Python Error: ModuleNotFoundError: No module named ‘spacy’
Error in <frozen importlib>_call_with_frames_removed (line 228)
Error in <frozen importlib>exec_module (line 850)
Error in <frozen importlib>_load_unlocked (line 680)
Any help will be appreciated.
The Matlab code is as follows
pe = pyenv;
disp(pe);
py.importlib.import_module(‘final_output’)
% Add the directory containing the Python script to the Python path
path_add = fileparts(which(‘final_output.py’));
if count(py.sys.path, path_add) == 0
insert(py.sys.path, int64(0), path_add);
end
% Define model path and text to process
model_path = ‘D:\output\model-best’;
text = ‘Roses are Red’;
% Call the Python function
pyOut = py.final_output.text_recognizer(model_path, text);
% Convert the output to a MATLAB cell array
entity_labels = cell(pyOut);
disp(entity_labels); I want to call a python function using Matlab. I am working on the NLP project, particularly text recognization. The name of the python file that I want to call using the Matlab is final_output.py. The final_output.py contains a import statement import spacy. This script run well when I run it using Pycharm. I installed all the required library using PyCharm terminal.
However, when I call the same python file from Matlab I received an error,
Error using final_output><module>
Python Error: ModuleNotFoundError: No module named ‘spacy’
Error in <frozen importlib>_call_with_frames_removed (line 228)
Error in <frozen importlib>exec_module (line 850)
Error in <frozen importlib>_load_unlocked (line 680)
Any help will be appreciated.
The Matlab code is as follows
pe = pyenv;
disp(pe);
py.importlib.import_module(‘final_output’)
% Add the directory containing the Python script to the Python path
path_add = fileparts(which(‘final_output.py’));
if count(py.sys.path, path_add) == 0
insert(py.sys.path, int64(0), path_add);
end
% Define model path and text to process
model_path = ‘D:\output\model-best’;
text = ‘Roses are Red’;
% Call the Python function
pyOut = py.final_output.text_recognizer(model_path, text);
% Convert the output to a MATLAB cell array
entity_labels = cell(pyOut);
disp(entity_labels); matlab, python MATLAB Answers — New Questions
Error in ode45 “inputs must be floats, namely single or double” when solving rocket flight equation.
Im trying to solve a non-linear first order differential equation with ode45, with a weird function thrust_cont thats supposed to describe the thrust of a model rocket.
syms v(t) a(t) y(t) thrust_complete(t) t diff_equation(t,v) thrust_cont(t) thrust_cont(t)
thrust_clean = [0,0.176;0.001,0.198;0.002,0.381;0.003,0.414;0.004,0.176;0.005,0.104;0.006,0.27;0.007,0.17;0.008,0.201;0.009,0.107;0.01,0.248;0.011,0.159;0.012,0.1……..rest of the data; this is [time in ms, Force]
thrust_clean (1634:20000,:) = 0;
for n=1634:1:20000
thrust_clean (n:20000,1) = n/1000;
end
grad = 100;
cf = polyfit(thrust_clean(1:1700,1), thrust_clean(1:1700,2),grad);
thrust_complete = 0;
for g = 1:grad
thrust_complete = thrust_complete + cf(g)*t^(grad+1-g);
end
thrust_cont = heaviside(t) * thrust_complete * heaviside(1.633-t);
fplot(thrust_cont, [0,2])
m = 0.14;
C_probar = 2.3;
rho = 1.29;
A = pi*0.05*0.05;
C_d = 0.75;
span = [0,20];
diff_equation = thrust_cont/m – 9.8 -((C_d*rho*A*C_probar/(m*2))*(v(t)^2));
[t, flight] = ode45(@(t,v) diff_equation, span, 0)
in the bold highlighted line i have my final version of the continous thrust curve function, which i had to manipulate quite a bit (cause im not very good at matlab unfortunately). Then i define a couple of normal variables, and then the problem, i define my equation (which the right hand side is equal to the derivative of v), and I try to use the ode45 function, only for it to return the following error message:
Error using superiorfloat
Inputs must be floats, namely single or double.
Error in odearguments (line 114)
dataType = superiorfloat(t0,y0,f0);
Error in ode45 (line 107)
odearguments(odeIsFuncHandle,odeTreatAsMFile, solver_name, ode, tspan, y0, options, varargin);
Error in TBD_matlab (line 23)
[t, flight] = ode45(@(t,v) diff_equation, span, 0)
I don’t even understand what the error is referring to or even trying to tell me, and I’ve been trying for quite some time now to move things around but nothing seems to work. I previously actually had tried to use dsolve to get an answer, but it found no analytical solution. If anybody has the slightest idea what could be happening i’d be grateful 👍Im trying to solve a non-linear first order differential equation with ode45, with a weird function thrust_cont thats supposed to describe the thrust of a model rocket.
syms v(t) a(t) y(t) thrust_complete(t) t diff_equation(t,v) thrust_cont(t) thrust_cont(t)
thrust_clean = [0,0.176;0.001,0.198;0.002,0.381;0.003,0.414;0.004,0.176;0.005,0.104;0.006,0.27;0.007,0.17;0.008,0.201;0.009,0.107;0.01,0.248;0.011,0.159;0.012,0.1……..rest of the data; this is [time in ms, Force]
thrust_clean (1634:20000,:) = 0;
for n=1634:1:20000
thrust_clean (n:20000,1) = n/1000;
end
grad = 100;
cf = polyfit(thrust_clean(1:1700,1), thrust_clean(1:1700,2),grad);
thrust_complete = 0;
for g = 1:grad
thrust_complete = thrust_complete + cf(g)*t^(grad+1-g);
end
thrust_cont = heaviside(t) * thrust_complete * heaviside(1.633-t);
fplot(thrust_cont, [0,2])
m = 0.14;
C_probar = 2.3;
rho = 1.29;
A = pi*0.05*0.05;
C_d = 0.75;
span = [0,20];
diff_equation = thrust_cont/m – 9.8 -((C_d*rho*A*C_probar/(m*2))*(v(t)^2));
[t, flight] = ode45(@(t,v) diff_equation, span, 0)
in the bold highlighted line i have my final version of the continous thrust curve function, which i had to manipulate quite a bit (cause im not very good at matlab unfortunately). Then i define a couple of normal variables, and then the problem, i define my equation (which the right hand side is equal to the derivative of v), and I try to use the ode45 function, only for it to return the following error message:
Error using superiorfloat
Inputs must be floats, namely single or double.
Error in odearguments (line 114)
dataType = superiorfloat(t0,y0,f0);
Error in ode45 (line 107)
odearguments(odeIsFuncHandle,odeTreatAsMFile, solver_name, ode, tspan, y0, options, varargin);
Error in TBD_matlab (line 23)
[t, flight] = ode45(@(t,v) diff_equation, span, 0)
I don’t even understand what the error is referring to or even trying to tell me, and I’ve been trying for quite some time now to move things around but nothing seems to work. I previously actually had tried to use dsolve to get an answer, but it found no analytical solution. If anybody has the slightest idea what could be happening i’d be grateful 👍 Im trying to solve a non-linear first order differential equation with ode45, with a weird function thrust_cont thats supposed to describe the thrust of a model rocket.
syms v(t) a(t) y(t) thrust_complete(t) t diff_equation(t,v) thrust_cont(t) thrust_cont(t)
thrust_clean = [0,0.176;0.001,0.198;0.002,0.381;0.003,0.414;0.004,0.176;0.005,0.104;0.006,0.27;0.007,0.17;0.008,0.201;0.009,0.107;0.01,0.248;0.011,0.159;0.012,0.1……..rest of the data; this is [time in ms, Force]
thrust_clean (1634:20000,:) = 0;
for n=1634:1:20000
thrust_clean (n:20000,1) = n/1000;
end
grad = 100;
cf = polyfit(thrust_clean(1:1700,1), thrust_clean(1:1700,2),grad);
thrust_complete = 0;
for g = 1:grad
thrust_complete = thrust_complete + cf(g)*t^(grad+1-g);
end
thrust_cont = heaviside(t) * thrust_complete * heaviside(1.633-t);
fplot(thrust_cont, [0,2])
m = 0.14;
C_probar = 2.3;
rho = 1.29;
A = pi*0.05*0.05;
C_d = 0.75;
span = [0,20];
diff_equation = thrust_cont/m – 9.8 -((C_d*rho*A*C_probar/(m*2))*(v(t)^2));
[t, flight] = ode45(@(t,v) diff_equation, span, 0)
in the bold highlighted line i have my final version of the continous thrust curve function, which i had to manipulate quite a bit (cause im not very good at matlab unfortunately). Then i define a couple of normal variables, and then the problem, i define my equation (which the right hand side is equal to the derivative of v), and I try to use the ode45 function, only for it to return the following error message:
Error using superiorfloat
Inputs must be floats, namely single or double.
Error in odearguments (line 114)
dataType = superiorfloat(t0,y0,f0);
Error in ode45 (line 107)
odearguments(odeIsFuncHandle,odeTreatAsMFile, solver_name, ode, tspan, y0, options, varargin);
Error in TBD_matlab (line 23)
[t, flight] = ode45(@(t,v) diff_equation, span, 0)
I don’t even understand what the error is referring to or even trying to tell me, and I’ve been trying for quite some time now to move things around but nothing seems to work. I previously actually had tried to use dsolve to get an answer, but it found no analytical solution. If anybody has the slightest idea what could be happening i’d be grateful 👍 ode45, matlab, differential equations MATLAB Answers — New Questions