Category: Matlab
Category Archives: Matlab
Not able to run simulations using Rapid accelerator
Running the example provide by Mathworks to simulate in rapid accelerator (sldemo_bounce) I got the following error message:
Top Model Build
1
Elapsed: 3 sec
### Building the rapid accelerator target for model: sldemo_bounce "INGWROOTbin/gcc" -c -fwrapv -m64 -O0 -DCLASSIC_INTERFACE=1 -DALLOCATIONFCN=0 -DONESTEPFCN=0 -DTERMFCN=1 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DEXT_MODE -DIS_RAPID_ACCEL -DTGTCONN -DIS_SIM_TARGET -DNRT -DRSIM_PARAMETER_LOADING -DRSIM_WITH_SL_SOLVER -DENABLE_SLEXEC_SSBRIDGE=1 -DMODEL_HAS_DYNAMICALLY_LOADED_SFCNS=0 -DON_TARGET_WAIT_FOR_START=0 -DTID01EQ=0 -DMODEL=sldemo_bounce -DNUMST=2 -DNCSTATES=2 -DHAVESTDIO @sldemo_bounce_comp.rsp -o "rt_logging_simtarget.obj" "C:/PROGRA~1/MATLAB/R2021a/rtw/c/src/rt_logging_simtarget.c" The system cannot find the path specified. gmake: *** [rt_logging_simtarget.obj] Error 1 The make command returned an error of 2 ### Build procedure for sldemo_bounce aborted due to an error.
Build Summary
1
Elapsed: 0.2 sec
Top model rapid accelerator targets built: Model Action Rebuild Reason ========================================================================= sldemo_bounce Failed Code generation information file does not exist. 0 of 1 models built (0 models already up to date) Build duration: 0h 0m 3.238s
Unable to build a standalone executable to simulate the model ‘sldemo_bounce’ in rapid accelerator mode.
Caused by:
Error(s) encountered while building "sldemo_bounce"
to run the simulation in rapid accelerator do I need the real time workshop tools license?
Regards
EduardoRunning the example provide by Mathworks to simulate in rapid accelerator (sldemo_bounce) I got the following error message:
Top Model Build
1
Elapsed: 3 sec
### Building the rapid accelerator target for model: sldemo_bounce "INGWROOTbin/gcc" -c -fwrapv -m64 -O0 -DCLASSIC_INTERFACE=1 -DALLOCATIONFCN=0 -DONESTEPFCN=0 -DTERMFCN=1 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DEXT_MODE -DIS_RAPID_ACCEL -DTGTCONN -DIS_SIM_TARGET -DNRT -DRSIM_PARAMETER_LOADING -DRSIM_WITH_SL_SOLVER -DENABLE_SLEXEC_SSBRIDGE=1 -DMODEL_HAS_DYNAMICALLY_LOADED_SFCNS=0 -DON_TARGET_WAIT_FOR_START=0 -DTID01EQ=0 -DMODEL=sldemo_bounce -DNUMST=2 -DNCSTATES=2 -DHAVESTDIO @sldemo_bounce_comp.rsp -o "rt_logging_simtarget.obj" "C:/PROGRA~1/MATLAB/R2021a/rtw/c/src/rt_logging_simtarget.c" The system cannot find the path specified. gmake: *** [rt_logging_simtarget.obj] Error 1 The make command returned an error of 2 ### Build procedure for sldemo_bounce aborted due to an error.
Build Summary
1
Elapsed: 0.2 sec
Top model rapid accelerator targets built: Model Action Rebuild Reason ========================================================================= sldemo_bounce Failed Code generation information file does not exist. 0 of 1 models built (0 models already up to date) Build duration: 0h 0m 3.238s
Unable to build a standalone executable to simulate the model ‘sldemo_bounce’ in rapid accelerator mode.
Caused by:
Error(s) encountered while building "sldemo_bounce"
to run the simulation in rapid accelerator do I need the real time workshop tools license?
Regards
Eduardo Running the example provide by Mathworks to simulate in rapid accelerator (sldemo_bounce) I got the following error message:
Top Model Build
1
Elapsed: 3 sec
### Building the rapid accelerator target for model: sldemo_bounce "INGWROOTbin/gcc" -c -fwrapv -m64 -O0 -DCLASSIC_INTERFACE=1 -DALLOCATIONFCN=0 -DONESTEPFCN=0 -DTERMFCN=1 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DEXT_MODE -DIS_RAPID_ACCEL -DTGTCONN -DIS_SIM_TARGET -DNRT -DRSIM_PARAMETER_LOADING -DRSIM_WITH_SL_SOLVER -DENABLE_SLEXEC_SSBRIDGE=1 -DMODEL_HAS_DYNAMICALLY_LOADED_SFCNS=0 -DON_TARGET_WAIT_FOR_START=0 -DTID01EQ=0 -DMODEL=sldemo_bounce -DNUMST=2 -DNCSTATES=2 -DHAVESTDIO @sldemo_bounce_comp.rsp -o "rt_logging_simtarget.obj" "C:/PROGRA~1/MATLAB/R2021a/rtw/c/src/rt_logging_simtarget.c" The system cannot find the path specified. gmake: *** [rt_logging_simtarget.obj] Error 1 The make command returned an error of 2 ### Build procedure for sldemo_bounce aborted due to an error.
Build Summary
1
Elapsed: 0.2 sec
Top model rapid accelerator targets built: Model Action Rebuild Reason ========================================================================= sldemo_bounce Failed Code generation information file does not exist. 0 of 1 models built (0 models already up to date) Build duration: 0h 0m 3.238s
Unable to build a standalone executable to simulate the model ‘sldemo_bounce’ in rapid accelerator mode.
Caused by:
Error(s) encountered while building "sldemo_bounce"
to run the simulation in rapid accelerator do I need the real time workshop tools license?
Regards
Eduardo simulink, rapid accelerator MATLAB Answers — New Questions
Can the output of plsregress be used to calculate Q residuals and T2 for new X data
Assume we have spectral data xcal, ycal, xval, yval where
xcal is mxn : m spectra, or observations, of a sample, n wavelengths per spectrum
ycal is mx1 : m concentrations of the sample corresponding to the m observations in xcal
xval is 1xn : 1 new spetrum or new observation of the sample (ie, not a member of xcal)
yval is 1×1 : 1 new concentration of the sample corresponding to the observation in xval
assuming m>n and ncomp<n and xcal0 is xcal with its mean subtracted,
xcal0 = xcal – ones(m,1)*mean(xcal)
[XL,YL,XS,YS,BETA,PCTVAR,MSE,STATS] = PLSREGRESS(xcal,ycal,ncomp);
Can be used to compute Q residuals, or the rowwise sum of squares of the STATS.XResiduals matrix
and
STATS.T2, is the Hotelling T^2 value
for each of the m observations in xcal
Q residuals and T2 values can be used to determine if the observations in xcal are outliers
Can the outputs of plsregress as described above be used to compute a Q residual and a T^2 value for the single observation in xval to determine if it seems to be an outlier with respect to xcal?Assume we have spectral data xcal, ycal, xval, yval where
xcal is mxn : m spectra, or observations, of a sample, n wavelengths per spectrum
ycal is mx1 : m concentrations of the sample corresponding to the m observations in xcal
xval is 1xn : 1 new spetrum or new observation of the sample (ie, not a member of xcal)
yval is 1×1 : 1 new concentration of the sample corresponding to the observation in xval
assuming m>n and ncomp<n and xcal0 is xcal with its mean subtracted,
xcal0 = xcal – ones(m,1)*mean(xcal)
[XL,YL,XS,YS,BETA,PCTVAR,MSE,STATS] = PLSREGRESS(xcal,ycal,ncomp);
Can be used to compute Q residuals, or the rowwise sum of squares of the STATS.XResiduals matrix
and
STATS.T2, is the Hotelling T^2 value
for each of the m observations in xcal
Q residuals and T2 values can be used to determine if the observations in xcal are outliers
Can the outputs of plsregress as described above be used to compute a Q residual and a T^2 value for the single observation in xval to determine if it seems to be an outlier with respect to xcal? Assume we have spectral data xcal, ycal, xval, yval where
xcal is mxn : m spectra, or observations, of a sample, n wavelengths per spectrum
ycal is mx1 : m concentrations of the sample corresponding to the m observations in xcal
xval is 1xn : 1 new spetrum or new observation of the sample (ie, not a member of xcal)
yval is 1×1 : 1 new concentration of the sample corresponding to the observation in xval
assuming m>n and ncomp<n and xcal0 is xcal with its mean subtracted,
xcal0 = xcal – ones(m,1)*mean(xcal)
[XL,YL,XS,YS,BETA,PCTVAR,MSE,STATS] = PLSREGRESS(xcal,ycal,ncomp);
Can be used to compute Q residuals, or the rowwise sum of squares of the STATS.XResiduals matrix
and
STATS.T2, is the Hotelling T^2 value
for each of the m observations in xcal
Q residuals and T2 values can be used to determine if the observations in xcal are outliers
Can the outputs of plsregress as described above be used to compute a Q residual and a T^2 value for the single observation in xval to determine if it seems to be an outlier with respect to xcal? plsregress q residuals, plsregress t2, plsregress outlier new data MATLAB Answers — New Questions
Convert string of nested field names to variable without eval?
Sorry if this is answered elsewhere, It wasn’t obvious to me from searching the archives that this exact question has been posed before.
I am parsing XML files using the function in File Exchange xml2struct (https://www.mathworks.com/matlabcentral/fileexchange/28518-xml2struct) which is a great tool, BTW.
As you might expected, the output is a nested structure, and depending on the input file, the field names and complexity of the structures are highly variable.
I am searching through theses structures to find a particular field of interest:
S.Data.Configuration.FieldofInterest
but in another file, that field might be on a completely different branch or level:
S2.Data.Nested.Field.FieldofInterest
I can generate list of strings with all the field names which I can parse to find the field of interest. But then I have some strings like this:
fnlist = ‘S.Data.Configuration.FieldofInterest’;
fnlist2 = ‘S2.Data.Nested.Field.FieldofInterest’;
If I want to extract the data from the fields of interest, the only way I know how to do this is to use eval:
output = eval(fnlist);
I’m not a fan of the eval functions because they make it very hard to debug code and diagnose problems if the string gets malformed.
I’d like to use dynamic field names like S.(name1).(name2).(name3), etc., but unless you know a priori the data structure and how many levels in your target field is (which I will not), this isn’t possible.
Is there another alternative besides eval? Thanks in advance.Sorry if this is answered elsewhere, It wasn’t obvious to me from searching the archives that this exact question has been posed before.
I am parsing XML files using the function in File Exchange xml2struct (https://www.mathworks.com/matlabcentral/fileexchange/28518-xml2struct) which is a great tool, BTW.
As you might expected, the output is a nested structure, and depending on the input file, the field names and complexity of the structures are highly variable.
I am searching through theses structures to find a particular field of interest:
S.Data.Configuration.FieldofInterest
but in another file, that field might be on a completely different branch or level:
S2.Data.Nested.Field.FieldofInterest
I can generate list of strings with all the field names which I can parse to find the field of interest. But then I have some strings like this:
fnlist = ‘S.Data.Configuration.FieldofInterest’;
fnlist2 = ‘S2.Data.Nested.Field.FieldofInterest’;
If I want to extract the data from the fields of interest, the only way I know how to do this is to use eval:
output = eval(fnlist);
I’m not a fan of the eval functions because they make it very hard to debug code and diagnose problems if the string gets malformed.
I’d like to use dynamic field names like S.(name1).(name2).(name3), etc., but unless you know a priori the data structure and how many levels in your target field is (which I will not), this isn’t possible.
Is there another alternative besides eval? Thanks in advance. Sorry if this is answered elsewhere, It wasn’t obvious to me from searching the archives that this exact question has been posed before.
I am parsing XML files using the function in File Exchange xml2struct (https://www.mathworks.com/matlabcentral/fileexchange/28518-xml2struct) which is a great tool, BTW.
As you might expected, the output is a nested structure, and depending on the input file, the field names and complexity of the structures are highly variable.
I am searching through theses structures to find a particular field of interest:
S.Data.Configuration.FieldofInterest
but in another file, that field might be on a completely different branch or level:
S2.Data.Nested.Field.FieldofInterest
I can generate list of strings with all the field names which I can parse to find the field of interest. But then I have some strings like this:
fnlist = ‘S.Data.Configuration.FieldofInterest’;
fnlist2 = ‘S2.Data.Nested.Field.FieldofInterest’;
If I want to extract the data from the fields of interest, the only way I know how to do this is to use eval:
output = eval(fnlist);
I’m not a fan of the eval functions because they make it very hard to debug code and diagnose problems if the string gets malformed.
I’d like to use dynamic field names like S.(name1).(name2).(name3), etc., but unless you know a priori the data structure and how many levels in your target field is (which I will not), this isn’t possible.
Is there another alternative besides eval? Thanks in advance. struct, eval, field names MATLAB Answers — New Questions
Can anyone please help ?
im trying to compute the steady solutions for the stream function and scalar vorticity for a 2d flow around an infinite cylinder at RE = 10
here is the question:
Here is the code:
function [psi, omega] = flow_around_cylinder_steady
Re=10;
%%%%% define the grid %%%%%
n=101; m=101; % number of grid points
N=n-1; M=m-1; % number of grid intervals
h=pi/M; % grid spacing based on theta variable
xi=(0:N)*h; theta=(0:M)*h; % xi and theta variables on the grid
%%%%% Initialize the flow fields %%%%%
psi=zeros(n,m);
omega=zeros(n,m);
psi(n,:)=exp(xi(n)) * sin(theta(:));
%%%%% Set relax params, tol, extra variables %%%%%
r_psi=1.8
r_omega=0.9
delta=1.e-08; % error tolerance
error=2*delta; % initialize error variable
%%%%% Add any additional variable definitions here %%%%%
…
…
%%%%% Main SOR Loop %%%%%
while (error > delta)
psi_old = psi; omega_old = omega;
for i=2:n-1
for j=2:m-1
psi(i,j)=exp(xi(i)) * sin(theta(j));
end
end
error_psi=max(abs(psi(:)-psi_old(:)));
omega(1,:)= (psi(3,j) – 8*psi(2,j)) * 1/(2*h^2);
for i=2:n-1
for j=2:m-1
omega_old(1,j)= (psi(3,j) – 8*psi(2,j)) * 1/(2*h^2);
end
end
error_omega=max(abs(omega(:)-omega_old(:)));
error=max(error_psi, error_omega);
end
plot_Re10(psi);
The code to call the function is:
[psi, omega] = flow_around_cylinder_steady;
But i get this:
The server timed out while running your solution. Potential reasons include inefficient code, an infinite loop, and excessive output. Try to improve your solution.
is there any way to improve it ?im trying to compute the steady solutions for the stream function and scalar vorticity for a 2d flow around an infinite cylinder at RE = 10
here is the question:
Here is the code:
function [psi, omega] = flow_around_cylinder_steady
Re=10;
%%%%% define the grid %%%%%
n=101; m=101; % number of grid points
N=n-1; M=m-1; % number of grid intervals
h=pi/M; % grid spacing based on theta variable
xi=(0:N)*h; theta=(0:M)*h; % xi and theta variables on the grid
%%%%% Initialize the flow fields %%%%%
psi=zeros(n,m);
omega=zeros(n,m);
psi(n,:)=exp(xi(n)) * sin(theta(:));
%%%%% Set relax params, tol, extra variables %%%%%
r_psi=1.8
r_omega=0.9
delta=1.e-08; % error tolerance
error=2*delta; % initialize error variable
%%%%% Add any additional variable definitions here %%%%%
…
…
%%%%% Main SOR Loop %%%%%
while (error > delta)
psi_old = psi; omega_old = omega;
for i=2:n-1
for j=2:m-1
psi(i,j)=exp(xi(i)) * sin(theta(j));
end
end
error_psi=max(abs(psi(:)-psi_old(:)));
omega(1,:)= (psi(3,j) – 8*psi(2,j)) * 1/(2*h^2);
for i=2:n-1
for j=2:m-1
omega_old(1,j)= (psi(3,j) – 8*psi(2,j)) * 1/(2*h^2);
end
end
error_omega=max(abs(omega(:)-omega_old(:)));
error=max(error_psi, error_omega);
end
plot_Re10(psi);
The code to call the function is:
[psi, omega] = flow_around_cylinder_steady;
But i get this:
The server timed out while running your solution. Potential reasons include inefficient code, an infinite loop, and excessive output. Try to improve your solution.
is there any way to improve it ? im trying to compute the steady solutions for the stream function and scalar vorticity for a 2d flow around an infinite cylinder at RE = 10
here is the question:
Here is the code:
function [psi, omega] = flow_around_cylinder_steady
Re=10;
%%%%% define the grid %%%%%
n=101; m=101; % number of grid points
N=n-1; M=m-1; % number of grid intervals
h=pi/M; % grid spacing based on theta variable
xi=(0:N)*h; theta=(0:M)*h; % xi and theta variables on the grid
%%%%% Initialize the flow fields %%%%%
psi=zeros(n,m);
omega=zeros(n,m);
psi(n,:)=exp(xi(n)) * sin(theta(:));
%%%%% Set relax params, tol, extra variables %%%%%
r_psi=1.8
r_omega=0.9
delta=1.e-08; % error tolerance
error=2*delta; % initialize error variable
%%%%% Add any additional variable definitions here %%%%%
…
…
%%%%% Main SOR Loop %%%%%
while (error > delta)
psi_old = psi; omega_old = omega;
for i=2:n-1
for j=2:m-1
psi(i,j)=exp(xi(i)) * sin(theta(j));
end
end
error_psi=max(abs(psi(:)-psi_old(:)));
omega(1,:)= (psi(3,j) – 8*psi(2,j)) * 1/(2*h^2);
for i=2:n-1
for j=2:m-1
omega_old(1,j)= (psi(3,j) – 8*psi(2,j)) * 1/(2*h^2);
end
end
error_omega=max(abs(omega(:)-omega_old(:)));
error=max(error_psi, error_omega);
end
plot_Re10(psi);
The code to call the function is:
[psi, omega] = flow_around_cylinder_steady;
But i get this:
The server timed out while running your solution. Potential reasons include inefficient code, an infinite loop, and excessive output. Try to improve your solution.
is there any way to improve it ? steady flow at re = 10, homework, assignment, exam question, cylinder MATLAB Answers — New Questions
How to generate a time signal from spectrum
Hello,
I’m working on spectrum comes from sea wave data.
I have a JONSWAP spectrum and I need to generate a signal in time domain to fed my numerical model of a floating body, can anybody suggest me how do it.Hello,
I’m working on spectrum comes from sea wave data.
I have a JONSWAP spectrum and I need to generate a signal in time domain to fed my numerical model of a floating body, can anybody suggest me how do it. Hello,
I’m working on spectrum comes from sea wave data.
I have a JONSWAP spectrum and I need to generate a signal in time domain to fed my numerical model of a floating body, can anybody suggest me how do it. signal, spectrum MATLAB Answers — New Questions
Hi I have a query I removed the harmonic to preserve the fundamental but still fundamental at 1MHz is also filtered can anyone tell m e.
% Load the frequency domain data
folder = ‘C:UsershaneuOneDrive바탕 화면dateNew folder (2)’;
filename = ‘270mvp.csv’;
data = readtable(fullfile(folder, filename));
% Extract frequency and FFT amplitude (assumed to be in dB)
f = table2array(data(3:end, 3)); % Frequency data (in Hz)
x_dB = table2array(data(3:end, 4)); % FFT amplitude data in dB
% Number of points in the FFT
N = length(x_dB);
% Compute the sampling frequency (fs)
% Assuming that your frequency axis (f) is spaced evenly
df = f(2) – f(1); % Frequency resolution
fs = N * df; % Sampling frequency
% Convert the amplitude from dB to linear scale
x_linear = 10.^(x_dB / 20);
% Compute the Power Spectral Density (PSD)
pxx = (x_linear.^2) / (fs * N);
% Convert PSD to dB/Hz
pxx_dBHz = 10 * log10(pxx);
% Fundamental frequency
f0 = 1e6; % 1 MHz
% Identify harmonic frequencies
harmonics = f0 * (1:floor(max(f)/f0));
% Remove harmonics from PSD
pxx_dBHz_filtered = pxx_dBHz; % Copy original PSD
for k = 1:length(harmonics)
harmonic_freq = harmonics(k);
[~, idx] = min(abs(f – harmonic_freq)); % Find the closest frequency index
pxx_dBHz_filtered(idx) = -Inf; % Set PSD of harmonics to -Inf (effectively removing)
end
% Plot the original Power Spectral Density (PSD)
figure;
subplot(2, 1, 1);
plot(f/1e6, pxx_dBHz);
xlabel(‘Frequency (MHz)’);
ylabel(‘PSD (dB/Hz)’);
title(‘Original Power Spectral Density (PSD)’);
% Plot the filtered Power Spectral Density (PSD)
subplot(2, 1, 2);
plot(f/1e6, pxx_dBHz_filtered);
xlabel(‘Frequency (MHz)’);
ylabel(‘PSD (dB/Hz)’);
title(‘Filtered Power Spectral Density (PSD)’);
% Highlight fundamental frequency in the plot
hold on;
plot(f0/1e6, pxx_dBHz_filtered(abs(f – f0) < df), ‘ro’, ‘MarkerSize’, 8, ‘LineWidth’, 2);
legend(‘Filtered PSD’, ‘Fundamental Frequency’);% Load the frequency domain data
folder = ‘C:UsershaneuOneDrive바탕 화면dateNew folder (2)’;
filename = ‘270mvp.csv’;
data = readtable(fullfile(folder, filename));
% Extract frequency and FFT amplitude (assumed to be in dB)
f = table2array(data(3:end, 3)); % Frequency data (in Hz)
x_dB = table2array(data(3:end, 4)); % FFT amplitude data in dB
% Number of points in the FFT
N = length(x_dB);
% Compute the sampling frequency (fs)
% Assuming that your frequency axis (f) is spaced evenly
df = f(2) – f(1); % Frequency resolution
fs = N * df; % Sampling frequency
% Convert the amplitude from dB to linear scale
x_linear = 10.^(x_dB / 20);
% Compute the Power Spectral Density (PSD)
pxx = (x_linear.^2) / (fs * N);
% Convert PSD to dB/Hz
pxx_dBHz = 10 * log10(pxx);
% Fundamental frequency
f0 = 1e6; % 1 MHz
% Identify harmonic frequencies
harmonics = f0 * (1:floor(max(f)/f0));
% Remove harmonics from PSD
pxx_dBHz_filtered = pxx_dBHz; % Copy original PSD
for k = 1:length(harmonics)
harmonic_freq = harmonics(k);
[~, idx] = min(abs(f – harmonic_freq)); % Find the closest frequency index
pxx_dBHz_filtered(idx) = -Inf; % Set PSD of harmonics to -Inf (effectively removing)
end
% Plot the original Power Spectral Density (PSD)
figure;
subplot(2, 1, 1);
plot(f/1e6, pxx_dBHz);
xlabel(‘Frequency (MHz)’);
ylabel(‘PSD (dB/Hz)’);
title(‘Original Power Spectral Density (PSD)’);
% Plot the filtered Power Spectral Density (PSD)
subplot(2, 1, 2);
plot(f/1e6, pxx_dBHz_filtered);
xlabel(‘Frequency (MHz)’);
ylabel(‘PSD (dB/Hz)’);
title(‘Filtered Power Spectral Density (PSD)’);
% Highlight fundamental frequency in the plot
hold on;
plot(f0/1e6, pxx_dBHz_filtered(abs(f – f0) < df), ‘ro’, ‘MarkerSize’, 8, ‘LineWidth’, 2);
legend(‘Filtered PSD’, ‘Fundamental Frequency’); % Load the frequency domain data
folder = ‘C:UsershaneuOneDrive바탕 화면dateNew folder (2)’;
filename = ‘270mvp.csv’;
data = readtable(fullfile(folder, filename));
% Extract frequency and FFT amplitude (assumed to be in dB)
f = table2array(data(3:end, 3)); % Frequency data (in Hz)
x_dB = table2array(data(3:end, 4)); % FFT amplitude data in dB
% Number of points in the FFT
N = length(x_dB);
% Compute the sampling frequency (fs)
% Assuming that your frequency axis (f) is spaced evenly
df = f(2) – f(1); % Frequency resolution
fs = N * df; % Sampling frequency
% Convert the amplitude from dB to linear scale
x_linear = 10.^(x_dB / 20);
% Compute the Power Spectral Density (PSD)
pxx = (x_linear.^2) / (fs * N);
% Convert PSD to dB/Hz
pxx_dBHz = 10 * log10(pxx);
% Fundamental frequency
f0 = 1e6; % 1 MHz
% Identify harmonic frequencies
harmonics = f0 * (1:floor(max(f)/f0));
% Remove harmonics from PSD
pxx_dBHz_filtered = pxx_dBHz; % Copy original PSD
for k = 1:length(harmonics)
harmonic_freq = harmonics(k);
[~, idx] = min(abs(f – harmonic_freq)); % Find the closest frequency index
pxx_dBHz_filtered(idx) = -Inf; % Set PSD of harmonics to -Inf (effectively removing)
end
% Plot the original Power Spectral Density (PSD)
figure;
subplot(2, 1, 1);
plot(f/1e6, pxx_dBHz);
xlabel(‘Frequency (MHz)’);
ylabel(‘PSD (dB/Hz)’);
title(‘Original Power Spectral Density (PSD)’);
% Plot the filtered Power Spectral Density (PSD)
subplot(2, 1, 2);
plot(f/1e6, pxx_dBHz_filtered);
xlabel(‘Frequency (MHz)’);
ylabel(‘PSD (dB/Hz)’);
title(‘Filtered Power Spectral Density (PSD)’);
% Highlight fundamental frequency in the plot
hold on;
plot(f0/1e6, pxx_dBHz_filtered(abs(f – f0) < df), ‘ro’, ‘MarkerSize’, 8, ‘LineWidth’, 2);
legend(‘Filtered PSD’, ‘Fundamental Frequency’); signal processing, filter MATLAB Answers — New Questions
Mex compiler MinGW64 only, although msvcpp xmls are in the mexopts folder
Hi,
I am having issues – for whatever reason my previous GPU compile for VS studio 2019 and Matlab 2022a got corrupted and now VS studio no longer offers VS 2019 download.
My exact issue is that the mex -setup C++ only finds MinGW64 and not the VS studio code (msvc2022) although it is in the mexopts folder and VS studio 2022 is download (including the manual C++ library installation).
Mathworks has xmls but it seems mex is not robust enough to find them and does not allow for manual addition of compilers (even though the xmls are thoroughly there in win64 folder. Does anyone have any ideas how to compile VS studio 2022 with whatever version of MATLAB that works with it.Hi,
I am having issues – for whatever reason my previous GPU compile for VS studio 2019 and Matlab 2022a got corrupted and now VS studio no longer offers VS 2019 download.
My exact issue is that the mex -setup C++ only finds MinGW64 and not the VS studio code (msvc2022) although it is in the mexopts folder and VS studio 2022 is download (including the manual C++ library installation).
Mathworks has xmls but it seems mex is not robust enough to find them and does not allow for manual addition of compilers (even though the xmls are thoroughly there in win64 folder. Does anyone have any ideas how to compile VS studio 2022 with whatever version of MATLAB that works with it. Hi,
I am having issues – for whatever reason my previous GPU compile for VS studio 2019 and Matlab 2022a got corrupted and now VS studio no longer offers VS 2019 download.
My exact issue is that the mex -setup C++ only finds MinGW64 and not the VS studio code (msvc2022) although it is in the mexopts folder and VS studio 2022 is download (including the manual C++ library installation).
Mathworks has xmls but it seems mex is not robust enough to find them and does not allow for manual addition of compilers (even though the xmls are thoroughly there in win64 folder. Does anyone have any ideas how to compile VS studio 2022 with whatever version of MATLAB that works with it. mex, mex compiler MATLAB Answers — New Questions
textprogress bar in parfor
this used to work in Matlab 2019b and before, to show a progressbar in parfor loop:
%% par pool
[~, output] = system(‘free -b | awk ”/Mem/{print $2}”’);
total_memory = str2double(output);
myCluster = min(ceil(total_memory / 1024^2 / 2 / 1000), round(maxNumCompThreads));
if isempty(gcp(‘nocreate’))
pool=parpool(myCluster,’IdleTimeout’, 604800);%1 week
end
nsim = 50
%% ———————————–
global P;
P = 1;
DataQueue = parallel.pool.DataQueue;
textprogressbar(‘start: ‘);
afterEach(DataQueue, @(ss) textprogressbar(P/nsim*100));
afterEach(DataQueue, @updateP);
parfor i = 1:nsim
send(DataQueue,i);
%someprocess
pause(0.1)
end
textprogressbar(‘ done’)
Now I updated to 2024a Update 4 (24.1.0.2628055). And even though the parloop run just fine, the progressbar is never updated.
Here the code of textprorgessbar I take somewhere from around here:
function textprogressbar(c)
% This function creates a text progress bar. It should be called with a
% STRING argument to initialize and terminate. Otherwise the number correspoding
% to progress in % should be supplied.
% INPUTS: C Either: Text string to initialize or terminate
% Percentage number to show progress
% OUTPUTS: N/A
% Example: Please refer to demo_textprogressbar.m
% Author: Paul Proteus (e-mail: proteus.paul (at) yahoo (dot) com)
% Version: 1.0
% Changes tracker: 29.06.2010 – First version
% Inspired by: http://blogs.mathworks.com/loren/2007/08/01/monitoring-progress-of-a-calculation/
%% Initialization
persistent strCR; % Carriage return pesistent variable
% Vizualization parameters
strPercentageLength = 6; % Length of percentage string (must be >5)
strDotsMaximum = 10; % The total number of dots in a progress bar
%% Main
if isempty(strCR) && ~ischar(c),
% Progress bar must be initialized with a string
error(‘The text progress must be initialized with a string’);
elseif isempty(strCR) && ischar(c),
% Progress bar – initialization
% fprintf(‘%s’,c);
tcprintf(‘green’,c);
strCR = -1;
elseif ~isempty(strCR) && ischar(c),
% Progress bar – termination
strCR = [];
% fprintf([c ‘n’]);
tcprintf(‘red’,[c ‘n’]);
elseif isnumeric(c)
% Progress bar – normal progress
c = floor(c);
percentageOut = [num2str(c) ‘%%’];
percentageOut = [percentageOut repmat(‘ ‘,1,strPercentageLength-length(percentageOut)-1)];
nDots = floor(c/100*strDotsMaximum);
dotOut = [‘[‘ repmat(‘.’,1,nDots) repmat(‘ ‘,1,strDotsMaximum-nDots) ‘]’];
strOut = [percentageOut dotOut];
% Print it on the screen BAR!!!!
if strCR == -1,
% Don’t do carriage return during first run
fprintf(strOut);
% tcprintf(‘yellow’,strOut);
else
% Do it during all the other runs
fprintf([strCR strOut]);
% tcprintf(‘yellow’,[strCR strOut]);
end
% Update carriage return
strCR = repmat(‘b’,1,length(strOut)-1);
else
% Any other unexpected input
error(‘Unsupported argument type’);
end
%%—————————————————
function tcprintf(style, fmatString, varargin)
% Uses ANSI escape codes to print colored output when using MATLAB
% from a terminal. If not running in a terminal, or if called by MATLAB’s
% datatipinfo function, tcprintf reverts to standard printf. The latter is
% desirable if tcprintf is used within an object’s disp() method to avoid
% seeing the ANSI characters here.
%
% The first argument is an style description that consists of space-separated
% words. These words may include:
%
% one of the following colors:
% black, red, green, yellow, blue, purple, cyan, darkGray, lightGray, white
%
% one of the following background colors:
% onBlack, onRed, onGreen, onYellow, onBlue, onPurple, onCyan, onWhite
%
% and any of the following modifiers:
% bright : use the bright (or bold) form of the color, not applicable for
% black, darkGray, lightGray, or white
% underline : draw an underline under each character
% blink : This is a mistake. Please don’t use this ever.
%
% Example:
% tcprintf(‘lightGray onRed underline’, ‘Message: %20sn’, msg);
%
% Author: Dan O’Shea dan at djoshea.com (c) 2012
%
% Released under the open source BSD license
% opensource.org/licenses/bsd-license.php
if nargin < 2 || ~ischar(style) || ~ischar(fmatString)
error(‘Usage: tcprintf(style, fmatString, …)’);
end
% determine if we’re using
usingTerminal = ~usejava(‘desktop’);
% determine if datatipinfo is higher on the stack. If tcprintf
% is used within an object’s disp() method, we don’t want to
% use color in the hover datatip or all you’ll see are ANSI codes.
stack = dbstack;
inDataTip = ismember(‘datatipinfo’, {stack.name});
if ~usingTerminal || inDataTip
% print the message without color and return
fprintf(fmatString, varargin{:});
return;
end
bright = 1;
[colorName backColorName bright underline blink] = parseStyle(style);
colorCodes = getColorCode(colorName, bright);
backColorCodes = getBackColorCode(backColorName);
codes = [colorCodes; backColorCodes];
if underline
codes = [codes; 4];
end
if blink
codes = [codes; 5];
end
codeStr = strjoin(codes, ‘;’);
% evaluate the printf style message
contents = sprintf(fmatString, varargin{:});
% if the message ends with a newline, we should turn off
% formatting before the newline to avoid issues with
% background colors
if ~isempty(contents) && contents(end) == char(10)
contents = contents(1:end-1);
endOfLine = char(10);
else
endOfLine = ”;
end
str = [’33[‘ codeStr ‘m’ contents ’33[0m’ endOfLine];
fprintf(str);
end
function [colorName backColorName bright underline blink] = parseStyle(style)
defaultColor = ‘white’;
defaultBackColor = ‘onDefault’;
tokens = regexp(style, ‘(?<value>S+)[s]?’, ‘names’);
values = {tokens.value};
if ismember(‘bright’, values)
bright = true;
else
bright = false;
end
if ismember(‘underline’, values)
underline = true;
else
underline = false;
end
if ismember(‘blink’, values)
blink = true;
else
blink = false;
end
% find foreground color
colorList = {‘black’, ‘darkGray’, ‘lightGray’, ‘red’, ‘green’, ‘yellow’, …
‘blue’, ‘purple’, ‘cyan’, ‘lightGray’, ‘white’, ‘default’};
idxColor = find(ismember(colorList, values), 1);
if ~isempty(idxColor)
colorName = colorList{idxColor};
else
colorName = defaultColor;
end
% find background color
backColorList = {‘onBlack’, ‘onRed’, ‘onGreen’, ‘onYellow’, ‘onBlue’, …
‘onPurple’, ‘onCyan’, ‘onWhite’, ‘onDefault’};
idxBackColor = find(ismember(backColorList, values), 1);
if ~isempty(idxBackColor)
backColorName = backColorList{idxBackColor};
else
backColorName = defaultBackColor;
end
end
function colorCodes = getColorCode(colorName, bright)
switch colorName
case ‘black’
code = 30;
bright = 0;
case ‘darkGray’;
code = 30;
bright = 1;
case ‘red’
code = 31;
case ‘green’
code = 32;
case ‘yellow’
code = 33;
case ‘blue’
code = 34;
case ‘purple’
code = 35;
case ‘cyan’
code = 36;
case ‘lightGray’
code = 37;
bright = 0;
case ‘white’
code = 37;
bright = 1;
case ‘default’
code = 39;
end
if bright
colorCodes = [1; code];
else
colorCodes = [code];
end
end
function colorCodes = getBackColorCode(colorName)
switch colorName
case ‘onBlack’
code = 40;
case ‘onRed’
code = 41;
case ‘onGreen’
code = 42;
case ‘onYellow’
code = 43;
case ‘onBlue’
code = 44;
case ‘onPurple’
code = 45;
case ‘onCyan’
code = 46;
case ‘onWhite’
code = 47;
case ‘onDefault’
code = 49;
end
colorCodes = code;
end
function str = strjoin(strCell, join)
% str = strjoin(strCell, join)
% creates a string by concatenating the elements of strCell, separated by the string
% in join (default = ‘, ‘)
%
% e.g. strCell = {‘a’,’b’}, join = ‘, ‘ [ default ] –> str = ‘a, b’
if nargin < 2
join = ‘, ‘;
end
if isempty(strCell)
str = ”;
else
if isnumeric(strCell) || islogical(strCell)
% convert numeric vectors to strings
strCell = arrayfun(@num2str, strCell, ‘UniformOutput’, false);
end
str = cellfun(@(str) [str join], strCell, …
‘UniformOutput’, false);
str = [str{:}];
str = str(1:end-length(join));
end
endthis used to work in Matlab 2019b and before, to show a progressbar in parfor loop:
%% par pool
[~, output] = system(‘free -b | awk ”/Mem/{print $2}”’);
total_memory = str2double(output);
myCluster = min(ceil(total_memory / 1024^2 / 2 / 1000), round(maxNumCompThreads));
if isempty(gcp(‘nocreate’))
pool=parpool(myCluster,’IdleTimeout’, 604800);%1 week
end
nsim = 50
%% ———————————–
global P;
P = 1;
DataQueue = parallel.pool.DataQueue;
textprogressbar(‘start: ‘);
afterEach(DataQueue, @(ss) textprogressbar(P/nsim*100));
afterEach(DataQueue, @updateP);
parfor i = 1:nsim
send(DataQueue,i);
%someprocess
pause(0.1)
end
textprogressbar(‘ done’)
Now I updated to 2024a Update 4 (24.1.0.2628055). And even though the parloop run just fine, the progressbar is never updated.
Here the code of textprorgessbar I take somewhere from around here:
function textprogressbar(c)
% This function creates a text progress bar. It should be called with a
% STRING argument to initialize and terminate. Otherwise the number correspoding
% to progress in % should be supplied.
% INPUTS: C Either: Text string to initialize or terminate
% Percentage number to show progress
% OUTPUTS: N/A
% Example: Please refer to demo_textprogressbar.m
% Author: Paul Proteus (e-mail: proteus.paul (at) yahoo (dot) com)
% Version: 1.0
% Changes tracker: 29.06.2010 – First version
% Inspired by: http://blogs.mathworks.com/loren/2007/08/01/monitoring-progress-of-a-calculation/
%% Initialization
persistent strCR; % Carriage return pesistent variable
% Vizualization parameters
strPercentageLength = 6; % Length of percentage string (must be >5)
strDotsMaximum = 10; % The total number of dots in a progress bar
%% Main
if isempty(strCR) && ~ischar(c),
% Progress bar must be initialized with a string
error(‘The text progress must be initialized with a string’);
elseif isempty(strCR) && ischar(c),
% Progress bar – initialization
% fprintf(‘%s’,c);
tcprintf(‘green’,c);
strCR = -1;
elseif ~isempty(strCR) && ischar(c),
% Progress bar – termination
strCR = [];
% fprintf([c ‘n’]);
tcprintf(‘red’,[c ‘n’]);
elseif isnumeric(c)
% Progress bar – normal progress
c = floor(c);
percentageOut = [num2str(c) ‘%%’];
percentageOut = [percentageOut repmat(‘ ‘,1,strPercentageLength-length(percentageOut)-1)];
nDots = floor(c/100*strDotsMaximum);
dotOut = [‘[‘ repmat(‘.’,1,nDots) repmat(‘ ‘,1,strDotsMaximum-nDots) ‘]’];
strOut = [percentageOut dotOut];
% Print it on the screen BAR!!!!
if strCR == -1,
% Don’t do carriage return during first run
fprintf(strOut);
% tcprintf(‘yellow’,strOut);
else
% Do it during all the other runs
fprintf([strCR strOut]);
% tcprintf(‘yellow’,[strCR strOut]);
end
% Update carriage return
strCR = repmat(‘b’,1,length(strOut)-1);
else
% Any other unexpected input
error(‘Unsupported argument type’);
end
%%—————————————————
function tcprintf(style, fmatString, varargin)
% Uses ANSI escape codes to print colored output when using MATLAB
% from a terminal. If not running in a terminal, or if called by MATLAB’s
% datatipinfo function, tcprintf reverts to standard printf. The latter is
% desirable if tcprintf is used within an object’s disp() method to avoid
% seeing the ANSI characters here.
%
% The first argument is an style description that consists of space-separated
% words. These words may include:
%
% one of the following colors:
% black, red, green, yellow, blue, purple, cyan, darkGray, lightGray, white
%
% one of the following background colors:
% onBlack, onRed, onGreen, onYellow, onBlue, onPurple, onCyan, onWhite
%
% and any of the following modifiers:
% bright : use the bright (or bold) form of the color, not applicable for
% black, darkGray, lightGray, or white
% underline : draw an underline under each character
% blink : This is a mistake. Please don’t use this ever.
%
% Example:
% tcprintf(‘lightGray onRed underline’, ‘Message: %20sn’, msg);
%
% Author: Dan O’Shea dan at djoshea.com (c) 2012
%
% Released under the open source BSD license
% opensource.org/licenses/bsd-license.php
if nargin < 2 || ~ischar(style) || ~ischar(fmatString)
error(‘Usage: tcprintf(style, fmatString, …)’);
end
% determine if we’re using
usingTerminal = ~usejava(‘desktop’);
% determine if datatipinfo is higher on the stack. If tcprintf
% is used within an object’s disp() method, we don’t want to
% use color in the hover datatip or all you’ll see are ANSI codes.
stack = dbstack;
inDataTip = ismember(‘datatipinfo’, {stack.name});
if ~usingTerminal || inDataTip
% print the message without color and return
fprintf(fmatString, varargin{:});
return;
end
bright = 1;
[colorName backColorName bright underline blink] = parseStyle(style);
colorCodes = getColorCode(colorName, bright);
backColorCodes = getBackColorCode(backColorName);
codes = [colorCodes; backColorCodes];
if underline
codes = [codes; 4];
end
if blink
codes = [codes; 5];
end
codeStr = strjoin(codes, ‘;’);
% evaluate the printf style message
contents = sprintf(fmatString, varargin{:});
% if the message ends with a newline, we should turn off
% formatting before the newline to avoid issues with
% background colors
if ~isempty(contents) && contents(end) == char(10)
contents = contents(1:end-1);
endOfLine = char(10);
else
endOfLine = ”;
end
str = [’33[‘ codeStr ‘m’ contents ’33[0m’ endOfLine];
fprintf(str);
end
function [colorName backColorName bright underline blink] = parseStyle(style)
defaultColor = ‘white’;
defaultBackColor = ‘onDefault’;
tokens = regexp(style, ‘(?<value>S+)[s]?’, ‘names’);
values = {tokens.value};
if ismember(‘bright’, values)
bright = true;
else
bright = false;
end
if ismember(‘underline’, values)
underline = true;
else
underline = false;
end
if ismember(‘blink’, values)
blink = true;
else
blink = false;
end
% find foreground color
colorList = {‘black’, ‘darkGray’, ‘lightGray’, ‘red’, ‘green’, ‘yellow’, …
‘blue’, ‘purple’, ‘cyan’, ‘lightGray’, ‘white’, ‘default’};
idxColor = find(ismember(colorList, values), 1);
if ~isempty(idxColor)
colorName = colorList{idxColor};
else
colorName = defaultColor;
end
% find background color
backColorList = {‘onBlack’, ‘onRed’, ‘onGreen’, ‘onYellow’, ‘onBlue’, …
‘onPurple’, ‘onCyan’, ‘onWhite’, ‘onDefault’};
idxBackColor = find(ismember(backColorList, values), 1);
if ~isempty(idxBackColor)
backColorName = backColorList{idxBackColor};
else
backColorName = defaultBackColor;
end
end
function colorCodes = getColorCode(colorName, bright)
switch colorName
case ‘black’
code = 30;
bright = 0;
case ‘darkGray’;
code = 30;
bright = 1;
case ‘red’
code = 31;
case ‘green’
code = 32;
case ‘yellow’
code = 33;
case ‘blue’
code = 34;
case ‘purple’
code = 35;
case ‘cyan’
code = 36;
case ‘lightGray’
code = 37;
bright = 0;
case ‘white’
code = 37;
bright = 1;
case ‘default’
code = 39;
end
if bright
colorCodes = [1; code];
else
colorCodes = [code];
end
end
function colorCodes = getBackColorCode(colorName)
switch colorName
case ‘onBlack’
code = 40;
case ‘onRed’
code = 41;
case ‘onGreen’
code = 42;
case ‘onYellow’
code = 43;
case ‘onBlue’
code = 44;
case ‘onPurple’
code = 45;
case ‘onCyan’
code = 46;
case ‘onWhite’
code = 47;
case ‘onDefault’
code = 49;
end
colorCodes = code;
end
function str = strjoin(strCell, join)
% str = strjoin(strCell, join)
% creates a string by concatenating the elements of strCell, separated by the string
% in join (default = ‘, ‘)
%
% e.g. strCell = {‘a’,’b’}, join = ‘, ‘ [ default ] –> str = ‘a, b’
if nargin < 2
join = ‘, ‘;
end
if isempty(strCell)
str = ”;
else
if isnumeric(strCell) || islogical(strCell)
% convert numeric vectors to strings
strCell = arrayfun(@num2str, strCell, ‘UniformOutput’, false);
end
str = cellfun(@(str) [str join], strCell, …
‘UniformOutput’, false);
str = [str{:}];
str = str(1:end-length(join));
end
end this used to work in Matlab 2019b and before, to show a progressbar in parfor loop:
%% par pool
[~, output] = system(‘free -b | awk ”/Mem/{print $2}”’);
total_memory = str2double(output);
myCluster = min(ceil(total_memory / 1024^2 / 2 / 1000), round(maxNumCompThreads));
if isempty(gcp(‘nocreate’))
pool=parpool(myCluster,’IdleTimeout’, 604800);%1 week
end
nsim = 50
%% ———————————–
global P;
P = 1;
DataQueue = parallel.pool.DataQueue;
textprogressbar(‘start: ‘);
afterEach(DataQueue, @(ss) textprogressbar(P/nsim*100));
afterEach(DataQueue, @updateP);
parfor i = 1:nsim
send(DataQueue,i);
%someprocess
pause(0.1)
end
textprogressbar(‘ done’)
Now I updated to 2024a Update 4 (24.1.0.2628055). And even though the parloop run just fine, the progressbar is never updated.
Here the code of textprorgessbar I take somewhere from around here:
function textprogressbar(c)
% This function creates a text progress bar. It should be called with a
% STRING argument to initialize and terminate. Otherwise the number correspoding
% to progress in % should be supplied.
% INPUTS: C Either: Text string to initialize or terminate
% Percentage number to show progress
% OUTPUTS: N/A
% Example: Please refer to demo_textprogressbar.m
% Author: Paul Proteus (e-mail: proteus.paul (at) yahoo (dot) com)
% Version: 1.0
% Changes tracker: 29.06.2010 – First version
% Inspired by: http://blogs.mathworks.com/loren/2007/08/01/monitoring-progress-of-a-calculation/
%% Initialization
persistent strCR; % Carriage return pesistent variable
% Vizualization parameters
strPercentageLength = 6; % Length of percentage string (must be >5)
strDotsMaximum = 10; % The total number of dots in a progress bar
%% Main
if isempty(strCR) && ~ischar(c),
% Progress bar must be initialized with a string
error(‘The text progress must be initialized with a string’);
elseif isempty(strCR) && ischar(c),
% Progress bar – initialization
% fprintf(‘%s’,c);
tcprintf(‘green’,c);
strCR = -1;
elseif ~isempty(strCR) && ischar(c),
% Progress bar – termination
strCR = [];
% fprintf([c ‘n’]);
tcprintf(‘red’,[c ‘n’]);
elseif isnumeric(c)
% Progress bar – normal progress
c = floor(c);
percentageOut = [num2str(c) ‘%%’];
percentageOut = [percentageOut repmat(‘ ‘,1,strPercentageLength-length(percentageOut)-1)];
nDots = floor(c/100*strDotsMaximum);
dotOut = [‘[‘ repmat(‘.’,1,nDots) repmat(‘ ‘,1,strDotsMaximum-nDots) ‘]’];
strOut = [percentageOut dotOut];
% Print it on the screen BAR!!!!
if strCR == -1,
% Don’t do carriage return during first run
fprintf(strOut);
% tcprintf(‘yellow’,strOut);
else
% Do it during all the other runs
fprintf([strCR strOut]);
% tcprintf(‘yellow’,[strCR strOut]);
end
% Update carriage return
strCR = repmat(‘b’,1,length(strOut)-1);
else
% Any other unexpected input
error(‘Unsupported argument type’);
end
%%—————————————————
function tcprintf(style, fmatString, varargin)
% Uses ANSI escape codes to print colored output when using MATLAB
% from a terminal. If not running in a terminal, or if called by MATLAB’s
% datatipinfo function, tcprintf reverts to standard printf. The latter is
% desirable if tcprintf is used within an object’s disp() method to avoid
% seeing the ANSI characters here.
%
% The first argument is an style description that consists of space-separated
% words. These words may include:
%
% one of the following colors:
% black, red, green, yellow, blue, purple, cyan, darkGray, lightGray, white
%
% one of the following background colors:
% onBlack, onRed, onGreen, onYellow, onBlue, onPurple, onCyan, onWhite
%
% and any of the following modifiers:
% bright : use the bright (or bold) form of the color, not applicable for
% black, darkGray, lightGray, or white
% underline : draw an underline under each character
% blink : This is a mistake. Please don’t use this ever.
%
% Example:
% tcprintf(‘lightGray onRed underline’, ‘Message: %20sn’, msg);
%
% Author: Dan O’Shea dan at djoshea.com (c) 2012
%
% Released under the open source BSD license
% opensource.org/licenses/bsd-license.php
if nargin < 2 || ~ischar(style) || ~ischar(fmatString)
error(‘Usage: tcprintf(style, fmatString, …)’);
end
% determine if we’re using
usingTerminal = ~usejava(‘desktop’);
% determine if datatipinfo is higher on the stack. If tcprintf
% is used within an object’s disp() method, we don’t want to
% use color in the hover datatip or all you’ll see are ANSI codes.
stack = dbstack;
inDataTip = ismember(‘datatipinfo’, {stack.name});
if ~usingTerminal || inDataTip
% print the message without color and return
fprintf(fmatString, varargin{:});
return;
end
bright = 1;
[colorName backColorName bright underline blink] = parseStyle(style);
colorCodes = getColorCode(colorName, bright);
backColorCodes = getBackColorCode(backColorName);
codes = [colorCodes; backColorCodes];
if underline
codes = [codes; 4];
end
if blink
codes = [codes; 5];
end
codeStr = strjoin(codes, ‘;’);
% evaluate the printf style message
contents = sprintf(fmatString, varargin{:});
% if the message ends with a newline, we should turn off
% formatting before the newline to avoid issues with
% background colors
if ~isempty(contents) && contents(end) == char(10)
contents = contents(1:end-1);
endOfLine = char(10);
else
endOfLine = ”;
end
str = [’33[‘ codeStr ‘m’ contents ’33[0m’ endOfLine];
fprintf(str);
end
function [colorName backColorName bright underline blink] = parseStyle(style)
defaultColor = ‘white’;
defaultBackColor = ‘onDefault’;
tokens = regexp(style, ‘(?<value>S+)[s]?’, ‘names’);
values = {tokens.value};
if ismember(‘bright’, values)
bright = true;
else
bright = false;
end
if ismember(‘underline’, values)
underline = true;
else
underline = false;
end
if ismember(‘blink’, values)
blink = true;
else
blink = false;
end
% find foreground color
colorList = {‘black’, ‘darkGray’, ‘lightGray’, ‘red’, ‘green’, ‘yellow’, …
‘blue’, ‘purple’, ‘cyan’, ‘lightGray’, ‘white’, ‘default’};
idxColor = find(ismember(colorList, values), 1);
if ~isempty(idxColor)
colorName = colorList{idxColor};
else
colorName = defaultColor;
end
% find background color
backColorList = {‘onBlack’, ‘onRed’, ‘onGreen’, ‘onYellow’, ‘onBlue’, …
‘onPurple’, ‘onCyan’, ‘onWhite’, ‘onDefault’};
idxBackColor = find(ismember(backColorList, values), 1);
if ~isempty(idxBackColor)
backColorName = backColorList{idxBackColor};
else
backColorName = defaultBackColor;
end
end
function colorCodes = getColorCode(colorName, bright)
switch colorName
case ‘black’
code = 30;
bright = 0;
case ‘darkGray’;
code = 30;
bright = 1;
case ‘red’
code = 31;
case ‘green’
code = 32;
case ‘yellow’
code = 33;
case ‘blue’
code = 34;
case ‘purple’
code = 35;
case ‘cyan’
code = 36;
case ‘lightGray’
code = 37;
bright = 0;
case ‘white’
code = 37;
bright = 1;
case ‘default’
code = 39;
end
if bright
colorCodes = [1; code];
else
colorCodes = [code];
end
end
function colorCodes = getBackColorCode(colorName)
switch colorName
case ‘onBlack’
code = 40;
case ‘onRed’
code = 41;
case ‘onGreen’
code = 42;
case ‘onYellow’
code = 43;
case ‘onBlue’
code = 44;
case ‘onPurple’
code = 45;
case ‘onCyan’
code = 46;
case ‘onWhite’
code = 47;
case ‘onDefault’
code = 49;
end
colorCodes = code;
end
function str = strjoin(strCell, join)
% str = strjoin(strCell, join)
% creates a string by concatenating the elements of strCell, separated by the string
% in join (default = ‘, ‘)
%
% e.g. strCell = {‘a’,’b’}, join = ‘, ‘ [ default ] –> str = ‘a, b’
if nargin < 2
join = ‘, ‘;
end
if isempty(strCell)
str = ”;
else
if isnumeric(strCell) || islogical(strCell)
% convert numeric vectors to strings
strCell = arrayfun(@num2str, strCell, ‘UniformOutput’, false);
end
str = cellfun(@(str) [str join], strCell, …
‘UniformOutput’, false);
str = [str{:}];
str = str(1:end-length(join));
end
end parfor, textprogressbar, 2024a MATLAB Answers — New Questions
Prevent error: “Unable to communicate with required MathWorks services (error 5001)”
I am encountering the error described in https://es.mathworks.com/matlabcentral/answers/1814080-why-do-i-receive-error-5001-unable-to-access-services-required-to-run-matlab#answer_1062795.
In my opinion this is not a good resolution. It is a very annoying error that is NOT properly addressed. In my case, I am running neuroimaging pipelines constantly and this bug continually breaks my runs. Is there any way to prevent this error from suddenly popping up that doesn’t involve having to kill processes? Ideally I would like to prevent it.
Im running R2024a.I am encountering the error described in https://es.mathworks.com/matlabcentral/answers/1814080-why-do-i-receive-error-5001-unable-to-access-services-required-to-run-matlab#answer_1062795.
In my opinion this is not a good resolution. It is a very annoying error that is NOT properly addressed. In my case, I am running neuroimaging pipelines constantly and this bug continually breaks my runs. Is there any way to prevent this error from suddenly popping up that doesn’t involve having to kill processes? Ideally I would like to prevent it.
Im running R2024a. I am encountering the error described in https://es.mathworks.com/matlabcentral/answers/1814080-why-do-i-receive-error-5001-unable-to-access-services-required-to-run-matlab#answer_1062795.
In my opinion this is not a good resolution. It is a very annoying error that is NOT properly addressed. In my case, I am running neuroimaging pipelines constantly and this bug continually breaks my runs. Is there any way to prevent this error from suddenly popping up that doesn’t involve having to kill processes? Ideally I would like to prevent it.
Im running R2024a. error 5001 MATLAB Answers — New Questions
ARIMA in Econometric Modeler
Hi,
I apologize for the simple question, but I’m very new to econometric analysis in MATLAB and not so experienced in Stata. Essentially, I have a database (attached Excel file) that I’m using to estimate an ARIMA(1,1,4) model for the variable "wpi". I’ve followed standard procedures in both Stata and MATLAB based on educational videos, but I’m receiving different coefficient estimates. I’ve made sure that both Stata and MATLAB use the first difference in the dependent variable, but I’m unsure what I’m doing wrong to get different estimates.
In fact, Stata Corp has a video on this exercise (https://www.youtube.com/watch?v=8xt4q7KHfBs), where the author [mistakenly used "wpi" instead of "log(wpi)"] and reports the results at minute 7:26. You can see the coefficient values there. When I fit the exact same model in MATLAB Econometric Modeller, my coefficient estimates are different. For example, the MATLAB constant estimate is 0.15, whereas in Stata it’s 0.74, and so on.
Could you please help me diagnose the problem? I’m attaching the dataset here. Thank you very much.Hi,
I apologize for the simple question, but I’m very new to econometric analysis in MATLAB and not so experienced in Stata. Essentially, I have a database (attached Excel file) that I’m using to estimate an ARIMA(1,1,4) model for the variable "wpi". I’ve followed standard procedures in both Stata and MATLAB based on educational videos, but I’m receiving different coefficient estimates. I’ve made sure that both Stata and MATLAB use the first difference in the dependent variable, but I’m unsure what I’m doing wrong to get different estimates.
In fact, Stata Corp has a video on this exercise (https://www.youtube.com/watch?v=8xt4q7KHfBs), where the author [mistakenly used "wpi" instead of "log(wpi)"] and reports the results at minute 7:26. You can see the coefficient values there. When I fit the exact same model in MATLAB Econometric Modeller, my coefficient estimates are different. For example, the MATLAB constant estimate is 0.15, whereas in Stata it’s 0.74, and so on.
Could you please help me diagnose the problem? I’m attaching the dataset here. Thank you very much. Hi,
I apologize for the simple question, but I’m very new to econometric analysis in MATLAB and not so experienced in Stata. Essentially, I have a database (attached Excel file) that I’m using to estimate an ARIMA(1,1,4) model for the variable "wpi". I’ve followed standard procedures in both Stata and MATLAB based on educational videos, but I’m receiving different coefficient estimates. I’ve made sure that both Stata and MATLAB use the first difference in the dependent variable, but I’m unsure what I’m doing wrong to get different estimates.
In fact, Stata Corp has a video on this exercise (https://www.youtube.com/watch?v=8xt4q7KHfBs), where the author [mistakenly used "wpi" instead of "log(wpi)"] and reports the results at minute 7:26. You can see the coefficient values there. When I fit the exact same model in MATLAB Econometric Modeller, my coefficient estimates are different. For example, the MATLAB constant estimate is 0.15, whereas in Stata it’s 0.74, and so on.
Could you please help me diagnose the problem? I’m attaching the dataset here. Thank you very much. econometric modeler, arima, stata MATLAB Answers — New Questions
2024a seems to have a graphics bug
A fresh install, on a macbook with the Apple M1 chip, and a total deletion of the ~/Library/Application Support/MathWorks files on Macos 14.6.1, when the first command is
close all
I get the following worring error:
>> close all
Warning: Initializing MATLAB Graphics failed.
This indicates a potentially serious problem in your MATLAB
setup, which should be resolved as soon as possible. Error
detected was:
MATLAB:minrhs
Not enough input arguments.
> In hgrc (line 154)
In matlab.graphics.internal.initialize (line 15)
>> plot(rand(1,10),rand(1,10))
>> close all
>> close all
>>
However, as can be seen, everything is fine once a plot has been made.
Best, JonA fresh install, on a macbook with the Apple M1 chip, and a total deletion of the ~/Library/Application Support/MathWorks files on Macos 14.6.1, when the first command is
close all
I get the following worring error:
>> close all
Warning: Initializing MATLAB Graphics failed.
This indicates a potentially serious problem in your MATLAB
setup, which should be resolved as soon as possible. Error
detected was:
MATLAB:minrhs
Not enough input arguments.
> In hgrc (line 154)
In matlab.graphics.internal.initialize (line 15)
>> plot(rand(1,10),rand(1,10))
>> close all
>> close all
>>
However, as can be seen, everything is fine once a plot has been made.
Best, Jon A fresh install, on a macbook with the Apple M1 chip, and a total deletion of the ~/Library/Application Support/MathWorks files on Macos 14.6.1, when the first command is
close all
I get the following worring error:
>> close all
Warning: Initializing MATLAB Graphics failed.
This indicates a potentially serious problem in your MATLAB
setup, which should be resolved as soon as possible. Error
detected was:
MATLAB:minrhs
Not enough input arguments.
> In hgrc (line 154)
In matlab.graphics.internal.initialize (line 15)
>> plot(rand(1,10),rand(1,10))
>> close all
>> close all
>>
However, as can be seen, everything is fine once a plot has been made.
Best, Jon initialization, graphics, failed, close MATLAB Answers — New Questions
Signal Processing Onramp (Preprocessing Signals — Extract Interesting Regions)
You can extract the data from the surface waves by removing extra points before and after. You can find the Extract Signals option in the Region of Interest section.
TASK
Extract the selected region from the harp, pax, and wanc signals. Make sure that the extracted signals are named harp_ROI, pax_ROI, and wanc_ROI respectively and display them.
Error I’m getting:
Have all three signals been cropped?You can extract the data from the surface waves by removing extra points before and after. You can find the Extract Signals option in the Region of Interest section.
TASK
Extract the selected region from the harp, pax, and wanc signals. Make sure that the extracted signals are named harp_ROI, pax_ROI, and wanc_ROI respectively and display them.
Error I’m getting:
Have all three signals been cropped? You can extract the data from the surface waves by removing extra points before and after. You can find the Extract Signals option in the Region of Interest section.
TASK
Extract the selected region from the harp, pax, and wanc signals. Make sure that the extracted signals are named harp_ROI, pax_ROI, and wanc_ROI respectively and display them.
Error I’m getting:
Have all three signals been cropped? signal processing, matlab MATLAB Answers — New Questions
Error: Index exceeds the number of array elements. Index must not exceed 2 (SIMULINK)
Hi there,
I have been running this simulation for months now but only suddenly is this giving this error. I have not changed it one bit (I think) and it suddenly can’t run. Please help!
run(‘PMDCcontrol.slx’)Hi there,
I have been running this simulation for months now but only suddenly is this giving this error. I have not changed it one bit (I think) and it suddenly can’t run. Please help!
run(‘PMDCcontrol.slx’) Hi there,
I have been running this simulation for months now but only suddenly is this giving this error. I have not changed it one bit (I think) and it suddenly can’t run. Please help!
run(‘PMDCcontrol.slx’) simulink, error MATLAB Answers — New Questions
How to use Aspen Plus – Matlab Link?
Please help me I am new to Matlab and Aspen Plus but have basic knowledge so please guide in detail. Please tell me what steps do I follow to link Aspen file and Matlab.
The Matlab cod file is:
%% Created by Ing. Andrés Felipe Abril. Universidad Nacional de Colombia. Departamento de Ingeniería Química.
%% Linking
Aspen = actxserver(‘Apwn.Document.36.0’); %34.0 —> V8.8; 35.0 —> V9.0; and 36.0 —> V10.0
[stat,mess]=fileattrib; % get attributes of folder (Necessary to establish the location of the simulation)
Simulation_Name = ‘Reactive_Distillation’;% Aspeen Plus Simulation Name
Aspen.invoke(‘InitFromArchive2’,[mess.Name ” Simulation_Name ‘.bkp’]);
Aspen.Visible = 1; % 1 —> Aspen is Visible; 0 —> Aspen is open but not visible
Aspen.SuppressDialogs = 1; % Suppress windows dialogs.
Aspen.Engine.Run2(1); % Run the simulation
while Aspen.Engine.IsRunning == 1 % 1 –> If Aspen is running; 0 —> If Aspen stop.
pause(0.5);
end
%% Example of Application
Reflux_Ratio = [1, 3, 5, 7];
for i = 1:length(Reflux_Ratio)
Aspen.Tree.FindNode("DataBlocksRC-101InputBASIS_RR").Value = Reflux_Ratio(i); % Column Reflux
Aspen.Reinit; % Reinit simulation
Aspen.Engine.Run2(1); %Run the simulation. (1) —> Matlab isnt busy; (0) Matlab is Busy;
time = 1;
while Aspen.Engine.IsRunning == 1 % 1 –> If Aspen is running; 0 —> If Aspen stop.
pause(0.5);
time = time+1;
if time==15 % Control of simulation time.
Aspen.Engine.Stop;
end
end
Simulation_Convergency = Aspen.Tree.FindNode("DataResults SummaryRun-StatusOutputPCESSTAT").Value; % 1 Doesn’t Convergence; 0 Converge
if Simulation_Convergency == 0 && time < 10
Duty(i) = Aspen.Tree.FindNode("DataBlocksRC-101OutputREB_UTL_DUTY").Value; %Duty value of reactive column
else
Duty(i) = inf; % Its Penalized if simulation doesn’t converge;
end
end
%% Plotting
figure()
plot(Reflux_Ratio, Duty, ‘ok’);
Aspen.Close;
Aspen.Quit;Please help me I am new to Matlab and Aspen Plus but have basic knowledge so please guide in detail. Please tell me what steps do I follow to link Aspen file and Matlab.
The Matlab cod file is:
%% Created by Ing. Andrés Felipe Abril. Universidad Nacional de Colombia. Departamento de Ingeniería Química.
%% Linking
Aspen = actxserver(‘Apwn.Document.36.0’); %34.0 —> V8.8; 35.0 —> V9.0; and 36.0 —> V10.0
[stat,mess]=fileattrib; % get attributes of folder (Necessary to establish the location of the simulation)
Simulation_Name = ‘Reactive_Distillation’;% Aspeen Plus Simulation Name
Aspen.invoke(‘InitFromArchive2’,[mess.Name ” Simulation_Name ‘.bkp’]);
Aspen.Visible = 1; % 1 —> Aspen is Visible; 0 —> Aspen is open but not visible
Aspen.SuppressDialogs = 1; % Suppress windows dialogs.
Aspen.Engine.Run2(1); % Run the simulation
while Aspen.Engine.IsRunning == 1 % 1 –> If Aspen is running; 0 —> If Aspen stop.
pause(0.5);
end
%% Example of Application
Reflux_Ratio = [1, 3, 5, 7];
for i = 1:length(Reflux_Ratio)
Aspen.Tree.FindNode("DataBlocksRC-101InputBASIS_RR").Value = Reflux_Ratio(i); % Column Reflux
Aspen.Reinit; % Reinit simulation
Aspen.Engine.Run2(1); %Run the simulation. (1) —> Matlab isnt busy; (0) Matlab is Busy;
time = 1;
while Aspen.Engine.IsRunning == 1 % 1 –> If Aspen is running; 0 —> If Aspen stop.
pause(0.5);
time = time+1;
if time==15 % Control of simulation time.
Aspen.Engine.Stop;
end
end
Simulation_Convergency = Aspen.Tree.FindNode("DataResults SummaryRun-StatusOutputPCESSTAT").Value; % 1 Doesn’t Convergence; 0 Converge
if Simulation_Convergency == 0 && time < 10
Duty(i) = Aspen.Tree.FindNode("DataBlocksRC-101OutputREB_UTL_DUTY").Value; %Duty value of reactive column
else
Duty(i) = inf; % Its Penalized if simulation doesn’t converge;
end
end
%% Plotting
figure()
plot(Reflux_Ratio, Duty, ‘ok’);
Aspen.Close;
Aspen.Quit; Please help me I am new to Matlab and Aspen Plus but have basic knowledge so please guide in detail. Please tell me what steps do I follow to link Aspen file and Matlab.
The Matlab cod file is:
%% Created by Ing. Andrés Felipe Abril. Universidad Nacional de Colombia. Departamento de Ingeniería Química.
%% Linking
Aspen = actxserver(‘Apwn.Document.36.0’); %34.0 —> V8.8; 35.0 —> V9.0; and 36.0 —> V10.0
[stat,mess]=fileattrib; % get attributes of folder (Necessary to establish the location of the simulation)
Simulation_Name = ‘Reactive_Distillation’;% Aspeen Plus Simulation Name
Aspen.invoke(‘InitFromArchive2’,[mess.Name ” Simulation_Name ‘.bkp’]);
Aspen.Visible = 1; % 1 —> Aspen is Visible; 0 —> Aspen is open but not visible
Aspen.SuppressDialogs = 1; % Suppress windows dialogs.
Aspen.Engine.Run2(1); % Run the simulation
while Aspen.Engine.IsRunning == 1 % 1 –> If Aspen is running; 0 —> If Aspen stop.
pause(0.5);
end
%% Example of Application
Reflux_Ratio = [1, 3, 5, 7];
for i = 1:length(Reflux_Ratio)
Aspen.Tree.FindNode("DataBlocksRC-101InputBASIS_RR").Value = Reflux_Ratio(i); % Column Reflux
Aspen.Reinit; % Reinit simulation
Aspen.Engine.Run2(1); %Run the simulation. (1) —> Matlab isnt busy; (0) Matlab is Busy;
time = 1;
while Aspen.Engine.IsRunning == 1 % 1 –> If Aspen is running; 0 —> If Aspen stop.
pause(0.5);
time = time+1;
if time==15 % Control of simulation time.
Aspen.Engine.Stop;
end
end
Simulation_Convergency = Aspen.Tree.FindNode("DataResults SummaryRun-StatusOutputPCESSTAT").Value; % 1 Doesn’t Convergence; 0 Converge
if Simulation_Convergency == 0 && time < 10
Duty(i) = Aspen.Tree.FindNode("DataBlocksRC-101OutputREB_UTL_DUTY").Value; %Duty value of reactive column
else
Duty(i) = inf; % Its Penalized if simulation doesn’t converge;
end
end
%% Plotting
figure()
plot(Reflux_Ratio, Duty, ‘ok’);
Aspen.Close;
Aspen.Quit; aspen plus MATLAB Answers — New Questions
how to model heat transfer to a pipe from furnace
Hello
I am trying to model a thermal fluid system where a furnace provides heat to pipe TL in simscape. at the moment, the mass flow rate of the fuel is 0, but i get the following errors:
At time 20.000000, one or more assertions are triggered. Temperature at port A must be less than or equal to Maximum valid temperature. The assertion comes from: Block path: pumpandpipe07082024/Pipe (TL)Assert location: o (location information is protected) o (location information is protected)
Ungroup 25 similar
Component:Simulink | Category:Model warning
An error occurred while running the simulation and the simulation was terminated
Caused by:
Derivative of state ‘pumpandpipe07082024.Pipe_TL.segment.p_I’ in block ‘pumpandpipe07082024/Pipe (TL)’ at time 50.0 is not finite. The simulation will be stopped. There may be a singularity in the solution. If not, try reducing the step size (either by reducing the fixed step size or by tightening the error tolerances)Hello
I am trying to model a thermal fluid system where a furnace provides heat to pipe TL in simscape. at the moment, the mass flow rate of the fuel is 0, but i get the following errors:
At time 20.000000, one or more assertions are triggered. Temperature at port A must be less than or equal to Maximum valid temperature. The assertion comes from: Block path: pumpandpipe07082024/Pipe (TL)Assert location: o (location information is protected) o (location information is protected)
Ungroup 25 similar
Component:Simulink | Category:Model warning
An error occurred while running the simulation and the simulation was terminated
Caused by:
Derivative of state ‘pumpandpipe07082024.Pipe_TL.segment.p_I’ in block ‘pumpandpipe07082024/Pipe (TL)’ at time 50.0 is not finite. The simulation will be stopped. There may be a singularity in the solution. If not, try reducing the step size (either by reducing the fixed step size or by tightening the error tolerances) Hello
I am trying to model a thermal fluid system where a furnace provides heat to pipe TL in simscape. at the moment, the mass flow rate of the fuel is 0, but i get the following errors:
At time 20.000000, one or more assertions are triggered. Temperature at port A must be less than or equal to Maximum valid temperature. The assertion comes from: Block path: pumpandpipe07082024/Pipe (TL)Assert location: o (location information is protected) o (location information is protected)
Ungroup 25 similar
Component:Simulink | Category:Model warning
An error occurred while running the simulation and the simulation was terminated
Caused by:
Derivative of state ‘pumpandpipe07082024.Pipe_TL.segment.p_I’ in block ‘pumpandpipe07082024/Pipe (TL)’ at time 50.0 is not finite. The simulation will be stopped. There may be a singularity in the solution. If not, try reducing the step size (either by reducing the fixed step size or by tightening the error tolerances) simscape, fluids, furnace MATLAB Answers — New Questions
Newton’s method gives NaN. Can someone improve my code?
Hello everybody. I’m using Newton’s method to solve a liner equation whose solution should be in [0 1]. Unfortunately, the coe I’m using gives NaN as a result for a specific combination of parameters and I would like to understand if I can improve the code I wrote for my Newton’s method. In the specific case I’m considering, I reach the maximum iterations even if the tolerance is very low.
function [x,n,ier] = newton(f,fd,x0,nmax,tol)
% Newton’s method for non-linear equations
ier = 0;
for n = 1:nmax
x = x0-f(x0)/fd(x0);
if abs(x-x0) <= tol
ier = 1;
break
end
x0 = x;
end
% % % % Script for solving NaN
mNAN= 16.1;
lNAN= 10^-4;
f= @(x) mNAN*x+lNAN*exp(mNAN*x)-lNAN*exp(mNAN);
Fd= @(x) mNAN*(1+lNAN*exp(mNAN*x));
tolNaN=10^-1;
nmax=10^8;
AB0 = 0.5;
[amNAN,nNAN,ierNAN]=newton(f,Fd,AB0,nmax,tolNaN);
amNAN
Llimit=f(0)
Ulimit=f(1)
fplot(@(x) mNAN*x+lNAN*exp(mNAN*x)-lNAN*exp(mNAN),[0 1.1])Hello everybody. I’m using Newton’s method to solve a liner equation whose solution should be in [0 1]. Unfortunately, the coe I’m using gives NaN as a result for a specific combination of parameters and I would like to understand if I can improve the code I wrote for my Newton’s method. In the specific case I’m considering, I reach the maximum iterations even if the tolerance is very low.
function [x,n,ier] = newton(f,fd,x0,nmax,tol)
% Newton’s method for non-linear equations
ier = 0;
for n = 1:nmax
x = x0-f(x0)/fd(x0);
if abs(x-x0) <= tol
ier = 1;
break
end
x0 = x;
end
% % % % Script for solving NaN
mNAN= 16.1;
lNAN= 10^-4;
f= @(x) mNAN*x+lNAN*exp(mNAN*x)-lNAN*exp(mNAN);
Fd= @(x) mNAN*(1+lNAN*exp(mNAN*x));
tolNaN=10^-1;
nmax=10^8;
AB0 = 0.5;
[amNAN,nNAN,ierNAN]=newton(f,Fd,AB0,nmax,tolNaN);
amNAN
Llimit=f(0)
Ulimit=f(1)
fplot(@(x) mNAN*x+lNAN*exp(mNAN*x)-lNAN*exp(mNAN),[0 1.1]) Hello everybody. I’m using Newton’s method to solve a liner equation whose solution should be in [0 1]. Unfortunately, the coe I’m using gives NaN as a result for a specific combination of parameters and I would like to understand if I can improve the code I wrote for my Newton’s method. In the specific case I’m considering, I reach the maximum iterations even if the tolerance is very low.
function [x,n,ier] = newton(f,fd,x0,nmax,tol)
% Newton’s method for non-linear equations
ier = 0;
for n = 1:nmax
x = x0-f(x0)/fd(x0);
if abs(x-x0) <= tol
ier = 1;
break
end
x0 = x;
end
% % % % Script for solving NaN
mNAN= 16.1;
lNAN= 10^-4;
f= @(x) mNAN*x+lNAN*exp(mNAN*x)-lNAN*exp(mNAN);
Fd= @(x) mNAN*(1+lNAN*exp(mNAN*x));
tolNaN=10^-1;
nmax=10^8;
AB0 = 0.5;
[amNAN,nNAN,ierNAN]=newton(f,Fd,AB0,nmax,tolNaN);
amNAN
Llimit=f(0)
Ulimit=f(1)
fplot(@(x) mNAN*x+lNAN*exp(mNAN*x)-lNAN*exp(mNAN),[0 1.1]) transferred MATLAB Answers — New Questions
Challenge with Simulating Loader Mechanism with Closed Kinematic Loop
I’m currently working on simulating a loader mechanism that includes a closed kinematic loop in its arm, actuated by two jacks. From my research, I understand that conducting a full multibody simulation in systems with a closed kinematic loop while all joints are actuated is impossible. Therefore, one of the actuators must be converted to an unactuated joint (Here is the Link for reference).
To address this, I left the right jack of the loader unactuated in my simulation and forced the left side to stay in a specific position, effectively conducting a static analysis (inverse dynamic) and recording the calculated forces on other joints, such as those between the chassis and the arm. Something like pictue below:
Here is my challenge:
When simulating the arm with only one active jack, the forces generated on the unactuated side of the loader are not accurate because the unactuated jack does not apply any force to the mechanism, which it does in reality. Am I correct in this understanding?
If so, how do others typically address this issue in their simulations?
Any insights or suggestions on how to properly simulate this mechanism would be greatly appreciated!I’m currently working on simulating a loader mechanism that includes a closed kinematic loop in its arm, actuated by two jacks. From my research, I understand that conducting a full multibody simulation in systems with a closed kinematic loop while all joints are actuated is impossible. Therefore, one of the actuators must be converted to an unactuated joint (Here is the Link for reference).
To address this, I left the right jack of the loader unactuated in my simulation and forced the left side to stay in a specific position, effectively conducting a static analysis (inverse dynamic) and recording the calculated forces on other joints, such as those between the chassis and the arm. Something like pictue below:
Here is my challenge:
When simulating the arm with only one active jack, the forces generated on the unactuated side of the loader are not accurate because the unactuated jack does not apply any force to the mechanism, which it does in reality. Am I correct in this understanding?
If so, how do others typically address this issue in their simulations?
Any insights or suggestions on how to properly simulate this mechanism would be greatly appreciated! I’m currently working on simulating a loader mechanism that includes a closed kinematic loop in its arm, actuated by two jacks. From my research, I understand that conducting a full multibody simulation in systems with a closed kinematic loop while all joints are actuated is impossible. Therefore, one of the actuators must be converted to an unactuated joint (Here is the Link for reference).
To address this, I left the right jack of the loader unactuated in my simulation and forced the left side to stay in a specific position, effectively conducting a static analysis (inverse dynamic) and recording the calculated forces on other joints, such as those between the chassis and the arm. Something like pictue below:
Here is my challenge:
When simulating the arm with only one active jack, the forces generated on the unactuated side of the loader are not accurate because the unactuated jack does not apply any force to the mechanism, which it does in reality. Am I correct in this understanding?
If so, how do others typically address this issue in their simulations?
Any insights or suggestions on how to properly simulate this mechanism would be greatly appreciated! simscape, simulation, guide MATLAB Answers — New Questions
Evaluate classification/regression performance against noisy annotation
Is there a way to evaluate classification/regression performance accounting of noisy annotations.
Let’s say I have a cat/dog detector and 1000 cat/dog test images. The 1000 images are human annotated, so it’s likely there are annotation errors, e.g. some bounding box may be incorrect and some class label may be wrong. Simply draw a confusion matrix or derive an IoU just compare the detector performance with the noisy data, and I don’t think such way is appropriate.
So my questions are
What’s the appropriate way to estimate the bbox and class error margin in the data set, given it’s not possible to go through each of them?
How to incorporate the above annotation error when reporting the performance of the cat/dog detector?
Thanks.Is there a way to evaluate classification/regression performance accounting of noisy annotations.
Let’s say I have a cat/dog detector and 1000 cat/dog test images. The 1000 images are human annotated, so it’s likely there are annotation errors, e.g. some bounding box may be incorrect and some class label may be wrong. Simply draw a confusion matrix or derive an IoU just compare the detector performance with the noisy data, and I don’t think such way is appropriate.
So my questions are
What’s the appropriate way to estimate the bbox and class error margin in the data set, given it’s not possible to go through each of them?
How to incorporate the above annotation error when reporting the performance of the cat/dog detector?
Thanks. Is there a way to evaluate classification/regression performance accounting of noisy annotations.
Let’s say I have a cat/dog detector and 1000 cat/dog test images. The 1000 images are human annotated, so it’s likely there are annotation errors, e.g. some bounding box may be incorrect and some class label may be wrong. Simply draw a confusion matrix or derive an IoU just compare the detector performance with the noisy data, and I don’t think such way is appropriate.
So my questions are
What’s the appropriate way to estimate the bbox and class error margin in the data set, given it’s not possible to go through each of them?
How to incorporate the above annotation error when reporting the performance of the cat/dog detector?
Thanks. annotation, classification, regression, noise, evaluation MATLAB Answers — New Questions
why my training results are repeated even after i run my code again and again ??
% ANN model for ukraine with all inputs
%% Data loading to the matlab environment
train_data = xlsread(‘Train_M.xlsx’);
input_train = xlsread(‘Train_M’,’input’);
X_train = input_train’;
target_train = xlsread(‘Train_M’,’target’);
T_train = target_train’;
test_data = xlsread(‘Test_M.xlsx’);
input_test = xlsread(‘Test_M’,’input’);
X_test = input_test’;
target_test = xlsread(‘Test_M’,’target’);
T_test = target_test’;
%% normalization of training and testing data
%for training
[Tr_i ps] = mapminmax(X_train,-1,1);
[Tr_t ps] = mapminmax(T_train,-1,1);
%for testing
[Tst_i pp] = mapminmax(X_test,-1,1);
[Tst_t pp] = mapminmax(T_test,-1,1);
%clear
%clc
%load Best_Dataset (need to save our datadivision for avoiding
%randomization)
%% GRNN model development
%% model formulation
spread = 0.42;
net = newgrnn(Tr_i,Tr_t,spread);
view(net);
%% prediction outputs of the model
y_tr = net(Tr_i);
y_tst = net(Tst_i);
%% renormalization process
% Model outputs(forecasted data)
Renorm_train_out = mapminmax(‘reverse’,y_tr,ps);
Renorm_test_out = mapminmax(‘reverse’,y_tst,pp);
%for model inputs(observed data)
Renorm_train_inp = mapminmax(‘reverse’,Tr_t,ps);
Renorm_test_inp = mapminmax(‘reverse’,Tst_t,pp);
%% performance of the ANN model
%Training performance and testing performance
plot(Renorm_test_inp,Renorm_test_out,’x’)%curves is ok
plot(Renorm_train_inp,Renorm_train_out,’x’)%curve is ok
%% statistical measure of the model
%% model performance command
mdl = fitlm(Renorm_test_inp,Renorm_test_out)%testing performance
mdl = fitlm(Renorm_train_inp,Renorm_train_out)%training performance
%% saving the trained model
save(‘GRNN_allinputs.mat’,’net’);
%% the results for the above code repeates.
R2 is 0.68, RMSE 10.8 – training
R2 is 0.639 ,RMSE 3.03 -testing
these results are again shown for the second run and so on
AM i missing something here ???
please help !!!!% ANN model for ukraine with all inputs
%% Data loading to the matlab environment
train_data = xlsread(‘Train_M.xlsx’);
input_train = xlsread(‘Train_M’,’input’);
X_train = input_train’;
target_train = xlsread(‘Train_M’,’target’);
T_train = target_train’;
test_data = xlsread(‘Test_M.xlsx’);
input_test = xlsread(‘Test_M’,’input’);
X_test = input_test’;
target_test = xlsread(‘Test_M’,’target’);
T_test = target_test’;
%% normalization of training and testing data
%for training
[Tr_i ps] = mapminmax(X_train,-1,1);
[Tr_t ps] = mapminmax(T_train,-1,1);
%for testing
[Tst_i pp] = mapminmax(X_test,-1,1);
[Tst_t pp] = mapminmax(T_test,-1,1);
%clear
%clc
%load Best_Dataset (need to save our datadivision for avoiding
%randomization)
%% GRNN model development
%% model formulation
spread = 0.42;
net = newgrnn(Tr_i,Tr_t,spread);
view(net);
%% prediction outputs of the model
y_tr = net(Tr_i);
y_tst = net(Tst_i);
%% renormalization process
% Model outputs(forecasted data)
Renorm_train_out = mapminmax(‘reverse’,y_tr,ps);
Renorm_test_out = mapminmax(‘reverse’,y_tst,pp);
%for model inputs(observed data)
Renorm_train_inp = mapminmax(‘reverse’,Tr_t,ps);
Renorm_test_inp = mapminmax(‘reverse’,Tst_t,pp);
%% performance of the ANN model
%Training performance and testing performance
plot(Renorm_test_inp,Renorm_test_out,’x’)%curves is ok
plot(Renorm_train_inp,Renorm_train_out,’x’)%curve is ok
%% statistical measure of the model
%% model performance command
mdl = fitlm(Renorm_test_inp,Renorm_test_out)%testing performance
mdl = fitlm(Renorm_train_inp,Renorm_train_out)%training performance
%% saving the trained model
save(‘GRNN_allinputs.mat’,’net’);
%% the results for the above code repeates.
R2 is 0.68, RMSE 10.8 – training
R2 is 0.639 ,RMSE 3.03 -testing
these results are again shown for the second run and so on
AM i missing something here ???
please help !!!! % ANN model for ukraine with all inputs
%% Data loading to the matlab environment
train_data = xlsread(‘Train_M.xlsx’);
input_train = xlsread(‘Train_M’,’input’);
X_train = input_train’;
target_train = xlsread(‘Train_M’,’target’);
T_train = target_train’;
test_data = xlsread(‘Test_M.xlsx’);
input_test = xlsread(‘Test_M’,’input’);
X_test = input_test’;
target_test = xlsread(‘Test_M’,’target’);
T_test = target_test’;
%% normalization of training and testing data
%for training
[Tr_i ps] = mapminmax(X_train,-1,1);
[Tr_t ps] = mapminmax(T_train,-1,1);
%for testing
[Tst_i pp] = mapminmax(X_test,-1,1);
[Tst_t pp] = mapminmax(T_test,-1,1);
%clear
%clc
%load Best_Dataset (need to save our datadivision for avoiding
%randomization)
%% GRNN model development
%% model formulation
spread = 0.42;
net = newgrnn(Tr_i,Tr_t,spread);
view(net);
%% prediction outputs of the model
y_tr = net(Tr_i);
y_tst = net(Tst_i);
%% renormalization process
% Model outputs(forecasted data)
Renorm_train_out = mapminmax(‘reverse’,y_tr,ps);
Renorm_test_out = mapminmax(‘reverse’,y_tst,pp);
%for model inputs(observed data)
Renorm_train_inp = mapminmax(‘reverse’,Tr_t,ps);
Renorm_test_inp = mapminmax(‘reverse’,Tst_t,pp);
%% performance of the ANN model
%Training performance and testing performance
plot(Renorm_test_inp,Renorm_test_out,’x’)%curves is ok
plot(Renorm_train_inp,Renorm_train_out,’x’)%curve is ok
%% statistical measure of the model
%% model performance command
mdl = fitlm(Renorm_test_inp,Renorm_test_out)%testing performance
mdl = fitlm(Renorm_train_inp,Renorm_train_out)%training performance
%% saving the trained model
save(‘GRNN_allinputs.mat’,’net’);
%% the results for the above code repeates.
R2 is 0.68, RMSE 10.8 – training
R2 is 0.639 ,RMSE 3.03 -testing
these results are again shown for the second run and so on
AM i missing something here ???
please help !!!! regression, general regression neural network, matlab, programming MATLAB Answers — New Questions
Why do I get “Maximum variable size allowed on the device is exceeded.” error when running the “semanticseg” function on my image and custom network?
I am trying to run the "semanticseg" function on an image with size (8557×11377) and my own custom network, and I receive the error:
ERROR: Error using nnet.internal.cnngpu.convolveForward2D
Maximum variable size allowed on the device is exceeded.
I expect MATLAB to tile the image, run the semantic segmentation, and reassemble the tile, but I am receiving this error on a windows laptop with a GTX 1070 card.
The two questions I have are:
1) Why do I receive this error message?
2) I would like to know what the maximum allowed image size I can have with my own custom network when running the "semanticseg" function.I am trying to run the "semanticseg" function on an image with size (8557×11377) and my own custom network, and I receive the error:
ERROR: Error using nnet.internal.cnngpu.convolveForward2D
Maximum variable size allowed on the device is exceeded.
I expect MATLAB to tile the image, run the semantic segmentation, and reassemble the tile, but I am receiving this error on a windows laptop with a GTX 1070 card.
The two questions I have are:
1) Why do I receive this error message?
2) I would like to know what the maximum allowed image size I can have with my own custom network when running the "semanticseg" function. I am trying to run the "semanticseg" function on an image with size (8557×11377) and my own custom network, and I receive the error:
ERROR: Error using nnet.internal.cnngpu.convolveForward2D
Maximum variable size allowed on the device is exceeded.
I expect MATLAB to tile the image, run the semantic segmentation, and reassemble the tile, but I am receiving this error on a windows laptop with a GTX 1070 card.
The two questions I have are:
1) Why do I receive this error message?
2) I would like to know what the maximum allowed image size I can have with my own custom network when running the "semanticseg" function. convolveforward2d, semanticseg MATLAB Answers — New Questions