Tag Archives: matlab
Create Timeseries Objekt in MATLAB with the property “StoredUnits”
I have various measured values in MATLAB and would like to convert them into a ‘timeseries’ object so that I can analyze them in SDI. To do this, however, the “StoredUnits” property of the ‘timeseries’ object must also be set so that the scaling for the data cursor can then be changed in SDI from, for example, “m/s” to “km/h.”
But “StoredUnits” is not offered in the properties of the ‘timeseries’ object.
% create timeseries-Objekt (example)
temp = timeseries(data, time, "Name", "test", "StoredUnits", "m/s")
Error:
Error using timeseries/init (line 153)
Invalid property name
The alternative method of loading the corresponding signal from the SDI into MATLAB and then setting the property results in the following message::
% get current run from SDI
countRun = Simulink.sdi.Run.getLatest;
% load respective signal
inSigID = getSignalByIndex(countRun, 1);
% set property
inSigID.StoredUnits = "m/s";
Error:
Unable to set the ‘StoredUnits’ property of class ‘Signal’ because it is read-only.
This raises the question: how can a ‘timeseries’ object with the “StoredUnits” property be created in MATLAB?I have various measured values in MATLAB and would like to convert them into a ‘timeseries’ object so that I can analyze them in SDI. To do this, however, the “StoredUnits” property of the ‘timeseries’ object must also be set so that the scaling for the data cursor can then be changed in SDI from, for example, “m/s” to “km/h.”
But “StoredUnits” is not offered in the properties of the ‘timeseries’ object.
% create timeseries-Objekt (example)
temp = timeseries(data, time, "Name", "test", "StoredUnits", "m/s")
Error:
Error using timeseries/init (line 153)
Invalid property name
The alternative method of loading the corresponding signal from the SDI into MATLAB and then setting the property results in the following message::
% get current run from SDI
countRun = Simulink.sdi.Run.getLatest;
% load respective signal
inSigID = getSignalByIndex(countRun, 1);
% set property
inSigID.StoredUnits = "m/s";
Error:
Unable to set the ‘StoredUnits’ property of class ‘Signal’ because it is read-only.
This raises the question: how can a ‘timeseries’ object with the “StoredUnits” property be created in MATLAB? I have various measured values in MATLAB and would like to convert them into a ‘timeseries’ object so that I can analyze them in SDI. To do this, however, the “StoredUnits” property of the ‘timeseries’ object must also be set so that the scaling for the data cursor can then be changed in SDI from, for example, “m/s” to “km/h.”
But “StoredUnits” is not offered in the properties of the ‘timeseries’ object.
% create timeseries-Objekt (example)
temp = timeseries(data, time, "Name", "test", "StoredUnits", "m/s")
Error:
Error using timeseries/init (line 153)
Invalid property name
The alternative method of loading the corresponding signal from the SDI into MATLAB and then setting the property results in the following message::
% get current run from SDI
countRun = Simulink.sdi.Run.getLatest;
% load respective signal
inSigID = getSignalByIndex(countRun, 1);
% set property
inSigID.StoredUnits = "m/s";
Error:
Unable to set the ‘StoredUnits’ property of class ‘Signal’ because it is read-only.
This raises the question: how can a ‘timeseries’ object with the “StoredUnits” property be created in MATLAB? sdi timeseries storedunits MATLAB Answers — New Questions
How can I set up Keycloak for use with MATLAB Web App Server?
I would like to set up Keycloak for authentication for MATLAB Web App Server, as I do not have my own identity provider. However, I am on Windows and cannot use the cloud reference architectures.
How do I manually set up Keycloak for authentication with MATLAB Web App Server?I would like to set up Keycloak for authentication for MATLAB Web App Server, as I do not have my own identity provider. However, I am on Windows and cannot use the cloud reference architectures.
How do I manually set up Keycloak for authentication with MATLAB Web App Server? I would like to set up Keycloak for authentication for MATLAB Web App Server, as I do not have my own identity provider. However, I am on Windows and cannot use the cloud reference architectures.
How do I manually set up Keycloak for authentication with MATLAB Web App Server? mwas, authnz MATLAB Answers — New Questions
I need my code to work/dont know what is going wrong.
I am working on a MATLAB assignment where I need to create a custom function called r_wheel.
The function should:
Take two inputs: bet_color and bet_amount
Return three outputs:
result_message (string saying if the bettor won or lost)
winner (0 if lost, 1 if won)
wager_message (string saying how much money was won or lost)
The payout rules are:
Red/Black → 1:1 payout
Green → 17:1 payout
If the bettor loses, they lose the amount wagered.
After that, I need to write a script that runs the function 100 times betting on "red" and calculates the odds of winning.
My issue is that I am not understanding how to get the function to be repeated multiple times and also add to a separate counter.
The error message I get is (Index exceeds the number of array elements. Index must not exceed 1.) Also, the code does not add to a counter, it instead only displays the answer one time.
This is the code for the function I made
function [result_msg,winner,wager_message] = r_wheel(bet_color, bet_amount)
disp(‘Spinning…’)
pause(2) %delay for suspense
random_int=randi([1 38]); %random # between 1 and 38
if random_int < 3 % if the # is less 1 or 2 then result is green
result_color = ‘Green’
wager_message = bet_amount*17 + bet_amount;
elseif (random_int <21) && (random_int>2)
result_color = ‘Red’ % if # is between 3 and 20 result is red
wager_message = bet_amount*2;
else
result_color = ‘Black’ %if # is between 21 and 38 the result is black
wager_message = bet_amount*2;
end
disp(result_color)
if strcmp(result_color, bet_color) % using string compare function to chekc if strings are the same
result_msg = ‘Congratulations! You win!’; % if bet color is correct set result to win
winner = 1; %set winner variable to 1
wager_message = wager_message
else
result_msg = ‘Sorry, you lose. Better luck next time!’; %if the bet color is not the same as result color set message
winner = 0; %set winner variable to 0
wager_message = -bet_amount
end
end
And here is the code for the loop.
clc, clear
x=’Red’
y= 15
win_count = 0
for i = 1:100
[result,winner]=r_wheel(x, y) % runs the function
win_count = 0
[result,winner]=r_wheel(x, y)
if winner(i)==1
win_count(i) = win_count(i)+1
else
win_count(i)= win_count(i)
end
end
disp(win_count)
disp(result)I am working on a MATLAB assignment where I need to create a custom function called r_wheel.
The function should:
Take two inputs: bet_color and bet_amount
Return three outputs:
result_message (string saying if the bettor won or lost)
winner (0 if lost, 1 if won)
wager_message (string saying how much money was won or lost)
The payout rules are:
Red/Black → 1:1 payout
Green → 17:1 payout
If the bettor loses, they lose the amount wagered.
After that, I need to write a script that runs the function 100 times betting on "red" and calculates the odds of winning.
My issue is that I am not understanding how to get the function to be repeated multiple times and also add to a separate counter.
The error message I get is (Index exceeds the number of array elements. Index must not exceed 1.) Also, the code does not add to a counter, it instead only displays the answer one time.
This is the code for the function I made
function [result_msg,winner,wager_message] = r_wheel(bet_color, bet_amount)
disp(‘Spinning…’)
pause(2) %delay for suspense
random_int=randi([1 38]); %random # between 1 and 38
if random_int < 3 % if the # is less 1 or 2 then result is green
result_color = ‘Green’
wager_message = bet_amount*17 + bet_amount;
elseif (random_int <21) && (random_int>2)
result_color = ‘Red’ % if # is between 3 and 20 result is red
wager_message = bet_amount*2;
else
result_color = ‘Black’ %if # is between 21 and 38 the result is black
wager_message = bet_amount*2;
end
disp(result_color)
if strcmp(result_color, bet_color) % using string compare function to chekc if strings are the same
result_msg = ‘Congratulations! You win!’; % if bet color is correct set result to win
winner = 1; %set winner variable to 1
wager_message = wager_message
else
result_msg = ‘Sorry, you lose. Better luck next time!’; %if the bet color is not the same as result color set message
winner = 0; %set winner variable to 0
wager_message = -bet_amount
end
end
And here is the code for the loop.
clc, clear
x=’Red’
y= 15
win_count = 0
for i = 1:100
[result,winner]=r_wheel(x, y) % runs the function
win_count = 0
[result,winner]=r_wheel(x, y)
if winner(i)==1
win_count(i) = win_count(i)+1
else
win_count(i)= win_count(i)
end
end
disp(win_count)
disp(result) I am working on a MATLAB assignment where I need to create a custom function called r_wheel.
The function should:
Take two inputs: bet_color and bet_amount
Return three outputs:
result_message (string saying if the bettor won or lost)
winner (0 if lost, 1 if won)
wager_message (string saying how much money was won or lost)
The payout rules are:
Red/Black → 1:1 payout
Green → 17:1 payout
If the bettor loses, they lose the amount wagered.
After that, I need to write a script that runs the function 100 times betting on "red" and calculates the odds of winning.
My issue is that I am not understanding how to get the function to be repeated multiple times and also add to a separate counter.
The error message I get is (Index exceeds the number of array elements. Index must not exceed 1.) Also, the code does not add to a counter, it instead only displays the answer one time.
This is the code for the function I made
function [result_msg,winner,wager_message] = r_wheel(bet_color, bet_amount)
disp(‘Spinning…’)
pause(2) %delay for suspense
random_int=randi([1 38]); %random # between 1 and 38
if random_int < 3 % if the # is less 1 or 2 then result is green
result_color = ‘Green’
wager_message = bet_amount*17 + bet_amount;
elseif (random_int <21) && (random_int>2)
result_color = ‘Red’ % if # is between 3 and 20 result is red
wager_message = bet_amount*2;
else
result_color = ‘Black’ %if # is between 21 and 38 the result is black
wager_message = bet_amount*2;
end
disp(result_color)
if strcmp(result_color, bet_color) % using string compare function to chekc if strings are the same
result_msg = ‘Congratulations! You win!’; % if bet color is correct set result to win
winner = 1; %set winner variable to 1
wager_message = wager_message
else
result_msg = ‘Sorry, you lose. Better luck next time!’; %if the bet color is not the same as result color set message
winner = 0; %set winner variable to 0
wager_message = -bet_amount
end
end
And here is the code for the loop.
clc, clear
x=’Red’
y= 15
win_count = 0
for i = 1:100
[result,winner]=r_wheel(x, y) % runs the function
win_count = 0
[result,winner]=r_wheel(x, y)
if winner(i)==1
win_count(i) = win_count(i)+1
else
win_count(i)= win_count(i)
end
end
disp(win_count)
disp(result) matlab code, help, error MATLAB Answers — New Questions
Can I configure a mex compiler on toolbox installation?
I have set of XML mexopts files and helper files that enable the use of the MinGW and Cygwin Fortran compilers on Windows on pre-R2024a releases. I’d like to package these in a toolbox like the compiler support package from Mathworks: https://www.mathworks.com/matlabcentral/fileexchange/52848-matlab-support-for-mingw-w64-c-c-fortran-compiler
On a fresh install of Matlab (i.e. mex not previously set up), installing that toolbox sets up the MinGW compilers. I don’t see a mechanism in the toolbox packaging tool to do this, though, and the only other answers I could find on this question suggest either having a check run the first time the user executes a toolbox function or having the user run a setup function.
Is there a way to do this automatically for user-created toolboxes?I have set of XML mexopts files and helper files that enable the use of the MinGW and Cygwin Fortran compilers on Windows on pre-R2024a releases. I’d like to package these in a toolbox like the compiler support package from Mathworks: https://www.mathworks.com/matlabcentral/fileexchange/52848-matlab-support-for-mingw-w64-c-c-fortran-compiler
On a fresh install of Matlab (i.e. mex not previously set up), installing that toolbox sets up the MinGW compilers. I don’t see a mechanism in the toolbox packaging tool to do this, though, and the only other answers I could find on this question suggest either having a check run the first time the user executes a toolbox function or having the user run a setup function.
Is there a way to do this automatically for user-created toolboxes? I have set of XML mexopts files and helper files that enable the use of the MinGW and Cygwin Fortran compilers on Windows on pre-R2024a releases. I’d like to package these in a toolbox like the compiler support package from Mathworks: https://www.mathworks.com/matlabcentral/fileexchange/52848-matlab-support-for-mingw-w64-c-c-fortran-compiler
On a fresh install of Matlab (i.e. mex not previously set up), installing that toolbox sets up the MinGW compilers. I don’t see a mechanism in the toolbox packaging tool to do this, though, and the only other answers I could find on this question suggest either having a check run the first time the user executes a toolbox function or having the user run a setup function.
Is there a way to do this automatically for user-created toolboxes? toolbox, mex MATLAB Answers — New Questions
Resetting a memoized function
I know that clearCache will clear the cache of a MemoizedFunction, but how would you reset its other properties to their defaults? I would have thought that rebuilding it with memoize() would do so, but the test below shows that that does not work.
mf=memoize(@localFcn) %default property values
mf.CacheSize=3; mf.Enabled=false %make some non-default property settings
clear mf
mf=memoize(@localFcn) %clear and rebuild — but property values do not reset!!!!
function y=localFcn(x)
y=x.^2;
endI know that clearCache will clear the cache of a MemoizedFunction, but how would you reset its other properties to their defaults? I would have thought that rebuilding it with memoize() would do so, but the test below shows that that does not work.
mf=memoize(@localFcn) %default property values
mf.CacheSize=3; mf.Enabled=false %make some non-default property settings
clear mf
mf=memoize(@localFcn) %clear and rebuild — but property values do not reset!!!!
function y=localFcn(x)
y=x.^2;
end I know that clearCache will clear the cache of a MemoizedFunction, but how would you reset its other properties to their defaults? I would have thought that rebuilding it with memoize() would do so, but the test below shows that that does not work.
mf=memoize(@localFcn) %default property values
mf.CacheSize=3; mf.Enabled=false %make some non-default property settings
clear mf
mf=memoize(@localFcn) %clear and rebuild — but property values do not reset!!!!
function y=localFcn(x)
y=x.^2;
end memoize MATLAB Answers — New Questions
How do I use ‘intersection’ to get the overlapping line between two polyshapes?
Hi – how do I get the line intersection between two polyshapes that overlap along a line? A super-simplified example is below. For the real case, the shapes are more complicated, but I think the simplified case covers it. I’m maybe not understanding how the intersection function works! Thank you!
function main()
%clear all; % completely superfluous in function workspace
x1 = [1 4 4 1];
y1 = [1 1 4 4];
x2 = [4 6 6 4];
y2 = [2 2 3 3];
poly1 = polyshape(x1,y1);
% the poly2 ‘grows’ from poly1
poly2 = polyshape(x2,y2);
poly2 = union(poly1,poly2);
growthPoly = subtract(poly2,poly1,"KeepCollinearPoints",true);
close all;
hold on;
plot(poly1,’FaceColor’,’none’,’EdgeColor’,’k’,’LineWidth’,12);
plot(poly2,’FaceColor’,’none’,’EdgeColor’,’g’,’LineWidth’,8);
plot(growthPoly,’FaceColor’,’none’,’EdgeColor’,’r’,’LineWidth’,4);
% this comes back empty and nothing gets plotted
growthLine = intersect(poly1,growthPoly,"KeepCollinearPoints",true);
plot(growthLine,’FaceColor’,’none’,’EdgeColor’,’b’,’LineWidth’,2);
legend({‘The initial poly1’,…
‘poly2 grew from poly1’,…
‘The growth area is the difference between poly2 and poly1′},’Box’,’off’,’Location’,’south’,’FontSize’,18);
title({‘How do I get the ”growthLine” part that is red-on-black?’;’I thought it would be the intersection of the black and red, but no dice’;’I thought it would show up as a blue line’},’FontSize’,22);
endHi – how do I get the line intersection between two polyshapes that overlap along a line? A super-simplified example is below. For the real case, the shapes are more complicated, but I think the simplified case covers it. I’m maybe not understanding how the intersection function works! Thank you!
function main()
%clear all; % completely superfluous in function workspace
x1 = [1 4 4 1];
y1 = [1 1 4 4];
x2 = [4 6 6 4];
y2 = [2 2 3 3];
poly1 = polyshape(x1,y1);
% the poly2 ‘grows’ from poly1
poly2 = polyshape(x2,y2);
poly2 = union(poly1,poly2);
growthPoly = subtract(poly2,poly1,"KeepCollinearPoints",true);
close all;
hold on;
plot(poly1,’FaceColor’,’none’,’EdgeColor’,’k’,’LineWidth’,12);
plot(poly2,’FaceColor’,’none’,’EdgeColor’,’g’,’LineWidth’,8);
plot(growthPoly,’FaceColor’,’none’,’EdgeColor’,’r’,’LineWidth’,4);
% this comes back empty and nothing gets plotted
growthLine = intersect(poly1,growthPoly,"KeepCollinearPoints",true);
plot(growthLine,’FaceColor’,’none’,’EdgeColor’,’b’,’LineWidth’,2);
legend({‘The initial poly1’,…
‘poly2 grew from poly1’,…
‘The growth area is the difference between poly2 and poly1′},’Box’,’off’,’Location’,’south’,’FontSize’,18);
title({‘How do I get the ”growthLine” part that is red-on-black?’;’I thought it would be the intersection of the black and red, but no dice’;’I thought it would show up as a blue line’},’FontSize’,22);
end Hi – how do I get the line intersection between two polyshapes that overlap along a line? A super-simplified example is below. For the real case, the shapes are more complicated, but I think the simplified case covers it. I’m maybe not understanding how the intersection function works! Thank you!
function main()
%clear all; % completely superfluous in function workspace
x1 = [1 4 4 1];
y1 = [1 1 4 4];
x2 = [4 6 6 4];
y2 = [2 2 3 3];
poly1 = polyshape(x1,y1);
% the poly2 ‘grows’ from poly1
poly2 = polyshape(x2,y2);
poly2 = union(poly1,poly2);
growthPoly = subtract(poly2,poly1,"KeepCollinearPoints",true);
close all;
hold on;
plot(poly1,’FaceColor’,’none’,’EdgeColor’,’k’,’LineWidth’,12);
plot(poly2,’FaceColor’,’none’,’EdgeColor’,’g’,’LineWidth’,8);
plot(growthPoly,’FaceColor’,’none’,’EdgeColor’,’r’,’LineWidth’,4);
% this comes back empty and nothing gets plotted
growthLine = intersect(poly1,growthPoly,"KeepCollinearPoints",true);
plot(growthLine,’FaceColor’,’none’,’EdgeColor’,’b’,’LineWidth’,2);
legend({‘The initial poly1’,…
‘poly2 grew from poly1’,…
‘The growth area is the difference between poly2 and poly1′},’Box’,’off’,’Location’,’south’,’FontSize’,18);
title({‘How do I get the ”growthLine” part that is red-on-black?’;’I thought it would be the intersection of the black and red, but no dice’;’I thought it would show up as a blue line’},’FontSize’,22);
end polyshape, intersection, union, subtract MATLAB Answers — New Questions
Why Does ifourier Not Return Equivalent Results for Equivalent Transforms?
Consider two expressions of a Fourier transform
syms t omega real
HU(omega) = -(exp(-omega*1i)*(exp(omega*1i) – 1)*(omega + 1i))/(omega*(omega^2 + 1))
Y(omega) = (exp(-omega*1i)*1i – 1i)/(omega*(1 + omega*1i))
The transforms are equivalent
simplify(HU(omega)-Y(omega))
so I would expect the inverse transforms to be equivalent.
Inverse transform of Y(omega)
y(t) = ifourier(Y(omega),omega,t)
Inverse transform of HU(omega)
hu(t) = ifourier(HU(omega),omega,t)
hu(t) looks complicated, but the primary concern is that Dirac delta in the first term in the numerator.
Simplify both expressions
s = @(z) simplify(rewrite(simplify(z),’heaviside’));
y(t) = s(y(t))
hu(t) = s(hu(t))
Sure enough, both time domain signals are the same with the exception that hu(t) includes that Dirac delta term.
Show that they are the same, except for the Dirac delta, by subtracting and using fplot that ignores Dirac delta terms:
figure
fplot(y(t)-hu(t),[-10,10]),ylim([-1e-16,1e-16])
Is this a bug, or is there a problem in the code, or am I misunderstanding what the results should be?Consider two expressions of a Fourier transform
syms t omega real
HU(omega) = -(exp(-omega*1i)*(exp(omega*1i) – 1)*(omega + 1i))/(omega*(omega^2 + 1))
Y(omega) = (exp(-omega*1i)*1i – 1i)/(omega*(1 + omega*1i))
The transforms are equivalent
simplify(HU(omega)-Y(omega))
so I would expect the inverse transforms to be equivalent.
Inverse transform of Y(omega)
y(t) = ifourier(Y(omega),omega,t)
Inverse transform of HU(omega)
hu(t) = ifourier(HU(omega),omega,t)
hu(t) looks complicated, but the primary concern is that Dirac delta in the first term in the numerator.
Simplify both expressions
s = @(z) simplify(rewrite(simplify(z),’heaviside’));
y(t) = s(y(t))
hu(t) = s(hu(t))
Sure enough, both time domain signals are the same with the exception that hu(t) includes that Dirac delta term.
Show that they are the same, except for the Dirac delta, by subtracting and using fplot that ignores Dirac delta terms:
figure
fplot(y(t)-hu(t),[-10,10]),ylim([-1e-16,1e-16])
Is this a bug, or is there a problem in the code, or am I misunderstanding what the results should be? Consider two expressions of a Fourier transform
syms t omega real
HU(omega) = -(exp(-omega*1i)*(exp(omega*1i) – 1)*(omega + 1i))/(omega*(omega^2 + 1))
Y(omega) = (exp(-omega*1i)*1i – 1i)/(omega*(1 + omega*1i))
The transforms are equivalent
simplify(HU(omega)-Y(omega))
so I would expect the inverse transforms to be equivalent.
Inverse transform of Y(omega)
y(t) = ifourier(Y(omega),omega,t)
Inverse transform of HU(omega)
hu(t) = ifourier(HU(omega),omega,t)
hu(t) looks complicated, but the primary concern is that Dirac delta in the first term in the numerator.
Simplify both expressions
s = @(z) simplify(rewrite(simplify(z),’heaviside’));
y(t) = s(y(t))
hu(t) = s(hu(t))
Sure enough, both time domain signals are the same with the exception that hu(t) includes that Dirac delta term.
Show that they are the same, except for the Dirac delta, by subtracting and using fplot that ignores Dirac delta terms:
figure
fplot(y(t)-hu(t),[-10,10]),ylim([-1e-16,1e-16])
Is this a bug, or is there a problem in the code, or am I misunderstanding what the results should be? ifourier, inconsistent results MATLAB Answers — New Questions
How to do 1D signal analysis?
I just need an example:
%% =========================
% [2.1] FFT calculation & plotting
% [2.5] Band power computation
% [1.1] Numerical integration (trapz)
% Custom PSD function (FFT-based periodogram)
% =========================
function [f, PSD] = myPSD(x, Fs)
x = x(:); % force column vector
x = x – mean(x); % remove DC offset
N = length(x);
X = fft(x);
K = floor(N/2); % one-sided spectrum length index
X = X(1:K+1);
% One-sided PSD estimate
PSD = (1/(Fs*N)) * abs(X).^2;
% Double interior bins (not DC / Nyquist)
if K > 1
PSD(2:end-1) = 2*PSD(2:end-1);
end
% Frequency vector (matches PSD length exactly)
f = (0:K)’ * (Fs/N);
end
%% Compute PSDs for original signals
[f1, PSD1] = myPSD(sig1, Fs);
[f2, PSD2] = myPSD(sig2, Fs);
%% Plot PSDs (same axes is what the lab asks)
% NOTE: If plotting linear PSD, ylabel should NOT be dB/Hz.
figure;
plot(f1, PSD1, ‘LineWidth’, 1.1); hold on;
plot(f2, PSD2, ‘LineWidth’, 1.1);
grid on;
xlim([0 200]);
xlabel("Frequency (Hz)");
ylabel("Power/Frequency (linear)");
title("PSD of Signal 1 and Signal 2");
legend("sig1","sig2");
% Optional dB version (more readable visually)
figure;
plot(f1, pow2db(PSD1), ‘LineWidth’, 1.1); hold on;
plot(f2, pow2db(PSD2), ‘LineWidth’, 1.1);
grid on;
xlim([0 200]);
xlabel("Frequency (Hz)");
ylabel("Power/Frequency (dB/Hz)");
title("PSD of Signal 1 and Signal 2 (dB)");
%% 20-100 Hz Bandpower using trapz
% [2.5] Band power computation
% [1.1] Numerical integration (trapz)
idx1 = (f1 >= 20) & (f1 <= 100);
idx2 = (f2 >= 20) & (f2 <= 100);
bandpower1 = trapz(f1(idx1), PSD1(idx1));
bandpower2 = trapz(f2(idx2), PSD2(idx2));
fprintf(‘Original bandpower (20-100 Hz): sig1 = %.6g, sig2 = %.6gn’, bandpower1, bandpower2);
%% =========================
% [1.5] Down-sampling
% Anti-aliasing before downsampling (Butterworth lowpass)
% =========================
Fs_down = 200; % new sampling rate (Nyquist = 100 Hz)
downFactor = Fs / Fs_down; % should be integer for downsample()
% Anti-alias lowpass filter (remove content above new Nyquist)
fc = 90; % use < 100 Hz for safety
order = 4;
Wn = fc / (Fs/2); % normalized cutoff
[b, a] = butter(order, Wn, ‘low’);
sig1_filt = filtfilt(b, a, sig1); % zero-phase filtering
sig2_filt = filtfilt(b, a, sig2);
% Downsample filtered signals
sig1_down = downsample(sig1_filt, downFactor);
sig2_down = downsample(sig2_filt, downFactor);
%% PSDs of anti-aliased + downsampled signals
[f1_down, PSD1_down] = myPSD(sig1_down, Fs_down);
[f2_down, PSD2_down] = myPSD(sig2_down, Fs_down);
figure;
plot(f1_down, PSD1_down, ‘LineWidth’, 1.1); hold on;
plot(f2_down, PSD2_down, ‘LineWidth’, 1.1);
grid on;
xlim([0 100]);
xlabel("Frequency (Hz)");
ylabel("Power/Frequency (linear)");
title("PSD of Downsampled Signals");
legend("sig1 down","sig2 down");
%% Bandpower (20-100 Hz) after anti-aliasing + downsampling
idx1_down = (f1_down >= 20) & (f1_down <= 100);
idx2_down = (f2_down >= 20) & (f2_down <= 100);
bandpower1_down = trapz(f1_down(idx1_down), PSD1_down(idx1_down));
bandpower2_down = trapz(f2_down(idx2_down), PSD2_down(idx2_down));
fprintf(‘Downsampled+AA bandpower (20-100 Hz): sig1 = %.6g, sig2 = %.6gn’, bandpower1_down, bandpower2_down);
%% =========================
% [1.4] Signal rectification & enveloping
% =========================
% Lab asks: rectify, then lowpass at 2 Hz to create heartbeat envelope
sig1_rect = abs(sig1_down);
sig2_rect = abs(sig2_down);
fc_env = 2; % envelope lowpass cutoff
order_env = 4;
Wn_env = fc_env / (Fs_down/2);
[b_env, a_env] = butter(order_env, Wn_env, ‘low’);
env1 = filtfilt(b_env, a_env, sig1_rect);
env2 = filtfilt(b_env, a_env, sig2_rect);
t1 = (0:length(env1)-1)’/Fs_down;
t2 = (0:length(env2)-1)’/Fs_down;
figure;
plot(t1, env1); grid on;
xlabel("Time (s)"); ylabel("Envelope amplitude");
title("Envelope of Signal 1");
figure;
plot(t2, env2); grid on;
xlabel("Time (s)"); ylabel("Envelope amplitude");
title("Envelope of Signal 2");
%% Rescale envelopes to [0,1] (helps peak detection)
env1_scaled = rescale(env1);
env2_scaled = rescale(env2);
figure;
plot(t1, env1_scaled); grid on;
xlabel("Time (s)"); ylabel("Scaled envelope");
title("Scaled Envelope of Signal 1");
figure;
plot(t2, env2_scaled); grid on;
xlabel("Time (s)"); ylabel("Scaled envelope");
title("Scaled Envelope of Signal 2");
%% =========================
% [1.2] Peak identification
% =========================
[pks1, locs1] = findpeaks(env1_scaled, ‘MinPeakProminence’, 0.1);
[pks2, locs2] = findpeaks(env2_scaled, ‘MinPeakProminence’, 0.1);
% Optional visualization of peaks
figure;
plot(t1, env1_scaled); hold on; grid on;
plot(locs1/Fs_down, pks1, ‘o’);
xlabel("Time (s)"); ylabel("Scaled envelope");
title("Signal 1 Peaks");
figure;
plot(t2, env2_scaled); hold on; grid on;
plot(locs2/Fs_down, pks2, ‘o’);
xlabel("Time (s)"); ylabel("Scaled envelope");
title("Signal 2 Peaks");
%% =========================
% [1.2] Peak timing -> Heart rate + beat-to-beat timing
% =========================
tpeaks1 = locs1 / Fs_down; % seconds
tpeaks2 = locs2 / Fs_down;
IBI1 = diff(tpeaks1); % inter-beat intervals (s)
IBI2 = diff(tpeaks2);
HR1_bpm = 60 / mean(IBI1); % average heart rate
HR2_bpm = 60 / mean(IBI2);
% Lab also asks for beat-to-beat timing variance
IBIvar1 = var(IBI1);
IBIvar2 = var(IBI2);
fprintf(‘HR sig1 = %.2f bpm, HR sig2 = %.2f bpmn’, HR1_bpm, HR2_bpm);
fprintf(‘Beat-to-beat variance: sig1 = %.6g s^2, sig2 = %.6g s^2n’, IBIvar1, IBIvar2);
%% =========================
% [1.5] Interpolation (recreate original sig1 from downsampled)
% Compare methods using RMSE
% =========================
t_down = (0:length(sig1_down)-1)’ / Fs_down;
t_orig = (0:length(sig1)-1)’ / Fs;
% Try a few methods (lab says experiment with interp1 methods)
methods = ["nearest","linear","spline","pchip","cubic"];
rmseVals = zeros(size(methods));
for k = 1:length(methods)
sig1_int = interp1(t_down, sig1_down, t_orig, methods(k))’;
rmseVals(k) = sqrt(mean((sig1 – sig1_int).^2, ‘omitnan’));
end
% Show RMSEs
disp(table(methods’, rmseVals’, ‘VariableNames’, {‘Method’,’RMSE’}));
% Pick best method (lowest RMSE)
[bestRMSE, idxBest] = min(rmseVals);
bestMethod = methods(idxBest);
% Recompute best interpolation for plotting
sig1_best = interp1(t_down, sig1_down, t_orig, bestMethod)’;
fprintf(‘Best interpolation method: %s (RMSE = %.6g)n’, bestMethod, bestRMSE);
% Plot original vs best interpolated (short window for visibility)
figure;
plot(t_orig, sig1, ‘LineWidth’, 1); hold on; grid on;
plot(t_orig, sig1_best, ‘–‘, ‘LineWidth’, 1);
xlim([0 2]); % zoom into first 2 s so differences are visible
xlabel("Time (s)"); ylabel("Amplitude");
title("Original sig1 vs Interpolated sig1");
legend("Original","Interpolated");I just need an example:
%% =========================
% [2.1] FFT calculation & plotting
% [2.5] Band power computation
% [1.1] Numerical integration (trapz)
% Custom PSD function (FFT-based periodogram)
% =========================
function [f, PSD] = myPSD(x, Fs)
x = x(:); % force column vector
x = x – mean(x); % remove DC offset
N = length(x);
X = fft(x);
K = floor(N/2); % one-sided spectrum length index
X = X(1:K+1);
% One-sided PSD estimate
PSD = (1/(Fs*N)) * abs(X).^2;
% Double interior bins (not DC / Nyquist)
if K > 1
PSD(2:end-1) = 2*PSD(2:end-1);
end
% Frequency vector (matches PSD length exactly)
f = (0:K)’ * (Fs/N);
end
%% Compute PSDs for original signals
[f1, PSD1] = myPSD(sig1, Fs);
[f2, PSD2] = myPSD(sig2, Fs);
%% Plot PSDs (same axes is what the lab asks)
% NOTE: If plotting linear PSD, ylabel should NOT be dB/Hz.
figure;
plot(f1, PSD1, ‘LineWidth’, 1.1); hold on;
plot(f2, PSD2, ‘LineWidth’, 1.1);
grid on;
xlim([0 200]);
xlabel("Frequency (Hz)");
ylabel("Power/Frequency (linear)");
title("PSD of Signal 1 and Signal 2");
legend("sig1","sig2");
% Optional dB version (more readable visually)
figure;
plot(f1, pow2db(PSD1), ‘LineWidth’, 1.1); hold on;
plot(f2, pow2db(PSD2), ‘LineWidth’, 1.1);
grid on;
xlim([0 200]);
xlabel("Frequency (Hz)");
ylabel("Power/Frequency (dB/Hz)");
title("PSD of Signal 1 and Signal 2 (dB)");
%% 20-100 Hz Bandpower using trapz
% [2.5] Band power computation
% [1.1] Numerical integration (trapz)
idx1 = (f1 >= 20) & (f1 <= 100);
idx2 = (f2 >= 20) & (f2 <= 100);
bandpower1 = trapz(f1(idx1), PSD1(idx1));
bandpower2 = trapz(f2(idx2), PSD2(idx2));
fprintf(‘Original bandpower (20-100 Hz): sig1 = %.6g, sig2 = %.6gn’, bandpower1, bandpower2);
%% =========================
% [1.5] Down-sampling
% Anti-aliasing before downsampling (Butterworth lowpass)
% =========================
Fs_down = 200; % new sampling rate (Nyquist = 100 Hz)
downFactor = Fs / Fs_down; % should be integer for downsample()
% Anti-alias lowpass filter (remove content above new Nyquist)
fc = 90; % use < 100 Hz for safety
order = 4;
Wn = fc / (Fs/2); % normalized cutoff
[b, a] = butter(order, Wn, ‘low’);
sig1_filt = filtfilt(b, a, sig1); % zero-phase filtering
sig2_filt = filtfilt(b, a, sig2);
% Downsample filtered signals
sig1_down = downsample(sig1_filt, downFactor);
sig2_down = downsample(sig2_filt, downFactor);
%% PSDs of anti-aliased + downsampled signals
[f1_down, PSD1_down] = myPSD(sig1_down, Fs_down);
[f2_down, PSD2_down] = myPSD(sig2_down, Fs_down);
figure;
plot(f1_down, PSD1_down, ‘LineWidth’, 1.1); hold on;
plot(f2_down, PSD2_down, ‘LineWidth’, 1.1);
grid on;
xlim([0 100]);
xlabel("Frequency (Hz)");
ylabel("Power/Frequency (linear)");
title("PSD of Downsampled Signals");
legend("sig1 down","sig2 down");
%% Bandpower (20-100 Hz) after anti-aliasing + downsampling
idx1_down = (f1_down >= 20) & (f1_down <= 100);
idx2_down = (f2_down >= 20) & (f2_down <= 100);
bandpower1_down = trapz(f1_down(idx1_down), PSD1_down(idx1_down));
bandpower2_down = trapz(f2_down(idx2_down), PSD2_down(idx2_down));
fprintf(‘Downsampled+AA bandpower (20-100 Hz): sig1 = %.6g, sig2 = %.6gn’, bandpower1_down, bandpower2_down);
%% =========================
% [1.4] Signal rectification & enveloping
% =========================
% Lab asks: rectify, then lowpass at 2 Hz to create heartbeat envelope
sig1_rect = abs(sig1_down);
sig2_rect = abs(sig2_down);
fc_env = 2; % envelope lowpass cutoff
order_env = 4;
Wn_env = fc_env / (Fs_down/2);
[b_env, a_env] = butter(order_env, Wn_env, ‘low’);
env1 = filtfilt(b_env, a_env, sig1_rect);
env2 = filtfilt(b_env, a_env, sig2_rect);
t1 = (0:length(env1)-1)’/Fs_down;
t2 = (0:length(env2)-1)’/Fs_down;
figure;
plot(t1, env1); grid on;
xlabel("Time (s)"); ylabel("Envelope amplitude");
title("Envelope of Signal 1");
figure;
plot(t2, env2); grid on;
xlabel("Time (s)"); ylabel("Envelope amplitude");
title("Envelope of Signal 2");
%% Rescale envelopes to [0,1] (helps peak detection)
env1_scaled = rescale(env1);
env2_scaled = rescale(env2);
figure;
plot(t1, env1_scaled); grid on;
xlabel("Time (s)"); ylabel("Scaled envelope");
title("Scaled Envelope of Signal 1");
figure;
plot(t2, env2_scaled); grid on;
xlabel("Time (s)"); ylabel("Scaled envelope");
title("Scaled Envelope of Signal 2");
%% =========================
% [1.2] Peak identification
% =========================
[pks1, locs1] = findpeaks(env1_scaled, ‘MinPeakProminence’, 0.1);
[pks2, locs2] = findpeaks(env2_scaled, ‘MinPeakProminence’, 0.1);
% Optional visualization of peaks
figure;
plot(t1, env1_scaled); hold on; grid on;
plot(locs1/Fs_down, pks1, ‘o’);
xlabel("Time (s)"); ylabel("Scaled envelope");
title("Signal 1 Peaks");
figure;
plot(t2, env2_scaled); hold on; grid on;
plot(locs2/Fs_down, pks2, ‘o’);
xlabel("Time (s)"); ylabel("Scaled envelope");
title("Signal 2 Peaks");
%% =========================
% [1.2] Peak timing -> Heart rate + beat-to-beat timing
% =========================
tpeaks1 = locs1 / Fs_down; % seconds
tpeaks2 = locs2 / Fs_down;
IBI1 = diff(tpeaks1); % inter-beat intervals (s)
IBI2 = diff(tpeaks2);
HR1_bpm = 60 / mean(IBI1); % average heart rate
HR2_bpm = 60 / mean(IBI2);
% Lab also asks for beat-to-beat timing variance
IBIvar1 = var(IBI1);
IBIvar2 = var(IBI2);
fprintf(‘HR sig1 = %.2f bpm, HR sig2 = %.2f bpmn’, HR1_bpm, HR2_bpm);
fprintf(‘Beat-to-beat variance: sig1 = %.6g s^2, sig2 = %.6g s^2n’, IBIvar1, IBIvar2);
%% =========================
% [1.5] Interpolation (recreate original sig1 from downsampled)
% Compare methods using RMSE
% =========================
t_down = (0:length(sig1_down)-1)’ / Fs_down;
t_orig = (0:length(sig1)-1)’ / Fs;
% Try a few methods (lab says experiment with interp1 methods)
methods = ["nearest","linear","spline","pchip","cubic"];
rmseVals = zeros(size(methods));
for k = 1:length(methods)
sig1_int = interp1(t_down, sig1_down, t_orig, methods(k))’;
rmseVals(k) = sqrt(mean((sig1 – sig1_int).^2, ‘omitnan’));
end
% Show RMSEs
disp(table(methods’, rmseVals’, ‘VariableNames’, {‘Method’,’RMSE’}));
% Pick best method (lowest RMSE)
[bestRMSE, idxBest] = min(rmseVals);
bestMethod = methods(idxBest);
% Recompute best interpolation for plotting
sig1_best = interp1(t_down, sig1_down, t_orig, bestMethod)’;
fprintf(‘Best interpolation method: %s (RMSE = %.6g)n’, bestMethod, bestRMSE);
% Plot original vs best interpolated (short window for visibility)
figure;
plot(t_orig, sig1, ‘LineWidth’, 1); hold on; grid on;
plot(t_orig, sig1_best, ‘–‘, ‘LineWidth’, 1);
xlim([0 2]); % zoom into first 2 s so differences are visible
xlabel("Time (s)"); ylabel("Amplitude");
title("Original sig1 vs Interpolated sig1");
legend("Original","Interpolated"); I just need an example:
%% =========================
% [2.1] FFT calculation & plotting
% [2.5] Band power computation
% [1.1] Numerical integration (trapz)
% Custom PSD function (FFT-based periodogram)
% =========================
function [f, PSD] = myPSD(x, Fs)
x = x(:); % force column vector
x = x – mean(x); % remove DC offset
N = length(x);
X = fft(x);
K = floor(N/2); % one-sided spectrum length index
X = X(1:K+1);
% One-sided PSD estimate
PSD = (1/(Fs*N)) * abs(X).^2;
% Double interior bins (not DC / Nyquist)
if K > 1
PSD(2:end-1) = 2*PSD(2:end-1);
end
% Frequency vector (matches PSD length exactly)
f = (0:K)’ * (Fs/N);
end
%% Compute PSDs for original signals
[f1, PSD1] = myPSD(sig1, Fs);
[f2, PSD2] = myPSD(sig2, Fs);
%% Plot PSDs (same axes is what the lab asks)
% NOTE: If plotting linear PSD, ylabel should NOT be dB/Hz.
figure;
plot(f1, PSD1, ‘LineWidth’, 1.1); hold on;
plot(f2, PSD2, ‘LineWidth’, 1.1);
grid on;
xlim([0 200]);
xlabel("Frequency (Hz)");
ylabel("Power/Frequency (linear)");
title("PSD of Signal 1 and Signal 2");
legend("sig1","sig2");
% Optional dB version (more readable visually)
figure;
plot(f1, pow2db(PSD1), ‘LineWidth’, 1.1); hold on;
plot(f2, pow2db(PSD2), ‘LineWidth’, 1.1);
grid on;
xlim([0 200]);
xlabel("Frequency (Hz)");
ylabel("Power/Frequency (dB/Hz)");
title("PSD of Signal 1 and Signal 2 (dB)");
%% 20-100 Hz Bandpower using trapz
% [2.5] Band power computation
% [1.1] Numerical integration (trapz)
idx1 = (f1 >= 20) & (f1 <= 100);
idx2 = (f2 >= 20) & (f2 <= 100);
bandpower1 = trapz(f1(idx1), PSD1(idx1));
bandpower2 = trapz(f2(idx2), PSD2(idx2));
fprintf(‘Original bandpower (20-100 Hz): sig1 = %.6g, sig2 = %.6gn’, bandpower1, bandpower2);
%% =========================
% [1.5] Down-sampling
% Anti-aliasing before downsampling (Butterworth lowpass)
% =========================
Fs_down = 200; % new sampling rate (Nyquist = 100 Hz)
downFactor = Fs / Fs_down; % should be integer for downsample()
% Anti-alias lowpass filter (remove content above new Nyquist)
fc = 90; % use < 100 Hz for safety
order = 4;
Wn = fc / (Fs/2); % normalized cutoff
[b, a] = butter(order, Wn, ‘low’);
sig1_filt = filtfilt(b, a, sig1); % zero-phase filtering
sig2_filt = filtfilt(b, a, sig2);
% Downsample filtered signals
sig1_down = downsample(sig1_filt, downFactor);
sig2_down = downsample(sig2_filt, downFactor);
%% PSDs of anti-aliased + downsampled signals
[f1_down, PSD1_down] = myPSD(sig1_down, Fs_down);
[f2_down, PSD2_down] = myPSD(sig2_down, Fs_down);
figure;
plot(f1_down, PSD1_down, ‘LineWidth’, 1.1); hold on;
plot(f2_down, PSD2_down, ‘LineWidth’, 1.1);
grid on;
xlim([0 100]);
xlabel("Frequency (Hz)");
ylabel("Power/Frequency (linear)");
title("PSD of Downsampled Signals");
legend("sig1 down","sig2 down");
%% Bandpower (20-100 Hz) after anti-aliasing + downsampling
idx1_down = (f1_down >= 20) & (f1_down <= 100);
idx2_down = (f2_down >= 20) & (f2_down <= 100);
bandpower1_down = trapz(f1_down(idx1_down), PSD1_down(idx1_down));
bandpower2_down = trapz(f2_down(idx2_down), PSD2_down(idx2_down));
fprintf(‘Downsampled+AA bandpower (20-100 Hz): sig1 = %.6g, sig2 = %.6gn’, bandpower1_down, bandpower2_down);
%% =========================
% [1.4] Signal rectification & enveloping
% =========================
% Lab asks: rectify, then lowpass at 2 Hz to create heartbeat envelope
sig1_rect = abs(sig1_down);
sig2_rect = abs(sig2_down);
fc_env = 2; % envelope lowpass cutoff
order_env = 4;
Wn_env = fc_env / (Fs_down/2);
[b_env, a_env] = butter(order_env, Wn_env, ‘low’);
env1 = filtfilt(b_env, a_env, sig1_rect);
env2 = filtfilt(b_env, a_env, sig2_rect);
t1 = (0:length(env1)-1)’/Fs_down;
t2 = (0:length(env2)-1)’/Fs_down;
figure;
plot(t1, env1); grid on;
xlabel("Time (s)"); ylabel("Envelope amplitude");
title("Envelope of Signal 1");
figure;
plot(t2, env2); grid on;
xlabel("Time (s)"); ylabel("Envelope amplitude");
title("Envelope of Signal 2");
%% Rescale envelopes to [0,1] (helps peak detection)
env1_scaled = rescale(env1);
env2_scaled = rescale(env2);
figure;
plot(t1, env1_scaled); grid on;
xlabel("Time (s)"); ylabel("Scaled envelope");
title("Scaled Envelope of Signal 1");
figure;
plot(t2, env2_scaled); grid on;
xlabel("Time (s)"); ylabel("Scaled envelope");
title("Scaled Envelope of Signal 2");
%% =========================
% [1.2] Peak identification
% =========================
[pks1, locs1] = findpeaks(env1_scaled, ‘MinPeakProminence’, 0.1);
[pks2, locs2] = findpeaks(env2_scaled, ‘MinPeakProminence’, 0.1);
% Optional visualization of peaks
figure;
plot(t1, env1_scaled); hold on; grid on;
plot(locs1/Fs_down, pks1, ‘o’);
xlabel("Time (s)"); ylabel("Scaled envelope");
title("Signal 1 Peaks");
figure;
plot(t2, env2_scaled); hold on; grid on;
plot(locs2/Fs_down, pks2, ‘o’);
xlabel("Time (s)"); ylabel("Scaled envelope");
title("Signal 2 Peaks");
%% =========================
% [1.2] Peak timing -> Heart rate + beat-to-beat timing
% =========================
tpeaks1 = locs1 / Fs_down; % seconds
tpeaks2 = locs2 / Fs_down;
IBI1 = diff(tpeaks1); % inter-beat intervals (s)
IBI2 = diff(tpeaks2);
HR1_bpm = 60 / mean(IBI1); % average heart rate
HR2_bpm = 60 / mean(IBI2);
% Lab also asks for beat-to-beat timing variance
IBIvar1 = var(IBI1);
IBIvar2 = var(IBI2);
fprintf(‘HR sig1 = %.2f bpm, HR sig2 = %.2f bpmn’, HR1_bpm, HR2_bpm);
fprintf(‘Beat-to-beat variance: sig1 = %.6g s^2, sig2 = %.6g s^2n’, IBIvar1, IBIvar2);
%% =========================
% [1.5] Interpolation (recreate original sig1 from downsampled)
% Compare methods using RMSE
% =========================
t_down = (0:length(sig1_down)-1)’ / Fs_down;
t_orig = (0:length(sig1)-1)’ / Fs;
% Try a few methods (lab says experiment with interp1 methods)
methods = ["nearest","linear","spline","pchip","cubic"];
rmseVals = zeros(size(methods));
for k = 1:length(methods)
sig1_int = interp1(t_down, sig1_down, t_orig, methods(k))’;
rmseVals(k) = sqrt(mean((sig1 – sig1_int).^2, ‘omitnan’));
end
% Show RMSEs
disp(table(methods’, rmseVals’, ‘VariableNames’, {‘Method’,’RMSE’}));
% Pick best method (lowest RMSE)
[bestRMSE, idxBest] = min(rmseVals);
bestMethod = methods(idxBest);
% Recompute best interpolation for plotting
sig1_best = interp1(t_down, sig1_down, t_orig, bestMethod)’;
fprintf(‘Best interpolation method: %s (RMSE = %.6g)n’, bestMethod, bestRMSE);
% Plot original vs best interpolated (short window for visibility)
figure;
plot(t_orig, sig1, ‘LineWidth’, 1); hold on; grid on;
plot(t_orig, sig1_best, ‘–‘, ‘LineWidth’, 1);
xlim([0 2]); % zoom into first 2 s so differences are visible
xlabel("Time (s)"); ylabel("Amplitude");
title("Original sig1 vs Interpolated sig1");
legend("Original","Interpolated"); signal processing MATLAB Answers — New Questions
Why do I receive error, “You do not have access to create LMS integrations for your account” when accessing MATLAB Grader?
I am trying to create an integration for my school. When I access MATLAB Grader, I come across a message saying "You do not have access to create LMS integrations for your account" How can I get access to create integrations?I am trying to create an integration for my school. When I access MATLAB Grader, I come across a message saying "You do not have access to create LMS integrations for your account" How can I get access to create integrations? I am trying to create an integration for my school. When I access MATLAB Grader, I come across a message saying "You do not have access to create LMS integrations for your account" How can I get access to create integrations? MATLAB Answers — New Questions
long time duration simulink simualtion stopped with error
An error occurred during simulation and the simulation was stopped
Caused by:
Output sample times of /Integer N PLL with Single Modulus Prescaler/Single Modulus Prescaler/Logic Decision1 occur out of sequence. Specify the ‘Minimum delay value’ parameter as a value greater than 1e-15 times the simulation stop time.
Component:Simulink | Category:Block errorAn error occurred during simulation and the simulation was stopped
Caused by:
Output sample times of /Integer N PLL with Single Modulus Prescaler/Single Modulus Prescaler/Logic Decision1 occur out of sequence. Specify the ‘Minimum delay value’ parameter as a value greater than 1e-15 times the simulation stop time.
Component:Simulink | Category:Block error An error occurred during simulation and the simulation was stopped
Caused by:
Output sample times of /Integer N PLL with Single Modulus Prescaler/Single Modulus Prescaler/Logic Decision1 occur out of sequence. Specify the ‘Minimum delay value’ parameter as a value greater than 1e-15 times the simulation stop time.
Component:Simulink | Category:Block error simulink, long time simulation, minimum delay value MATLAB Answers — New Questions
Matlab using parallels on M1 macbook pro
Hello,
For the purpose of research, I need to use a image analysis program designed for windows, that requires matlab, which is run using parallels on macs with intel-processors. I’m currently looking at purchasing a new macbook pro m1 for work. Collegues have warned me that it’s only possible to run the insider preview ARM-based windows 11, not x86, using parallels on macbook M1, which is, if I understand this correctly, not compatible with matlab, and therefore I cannot run the programs needed for work. Do anyone know any solution to this problem? I would be most thankful.Hello,
For the purpose of research, I need to use a image analysis program designed for windows, that requires matlab, which is run using parallels on macs with intel-processors. I’m currently looking at purchasing a new macbook pro m1 for work. Collegues have warned me that it’s only possible to run the insider preview ARM-based windows 11, not x86, using parallels on macbook M1, which is, if I understand this correctly, not compatible with matlab, and therefore I cannot run the programs needed for work. Do anyone know any solution to this problem? I would be most thankful. Hello,
For the purpose of research, I need to use a image analysis program designed for windows, that requires matlab, which is run using parallels on macs with intel-processors. I’m currently looking at purchasing a new macbook pro m1 for work. Collegues have warned me that it’s only possible to run the insider preview ARM-based windows 11, not x86, using parallels on macbook M1, which is, if I understand this correctly, not compatible with matlab, and therefore I cannot run the programs needed for work. Do anyone know any solution to this problem? I would be most thankful. mac, m1, parallels MATLAB Answers — New Questions
scanf/printf not working when calling generated C code
In Matlab I have generated C code (.c/.h files) from a Matlab function using codegen from Matlab Coder.
I call this function in a while loop on an ARM quad-core Cortex A53 using AMD Vitis.
Before calling this function I use scanf/printf to get user input and to print to the serial monitor. However, scanf/printf only work once in the 1st iteration (before calling the function) and not in the 2nd iteration or later (after calling the function).
Is this a common problem and has anyone encountered this problem before?
I think, but am not sure, that the problem is in the generated C code and not in Vitis itself.
Thank you in advance!In Matlab I have generated C code (.c/.h files) from a Matlab function using codegen from Matlab Coder.
I call this function in a while loop on an ARM quad-core Cortex A53 using AMD Vitis.
Before calling this function I use scanf/printf to get user input and to print to the serial monitor. However, scanf/printf only work once in the 1st iteration (before calling the function) and not in the 2nd iteration or later (after calling the function).
Is this a common problem and has anyone encountered this problem before?
I think, but am not sure, that the problem is in the generated C code and not in Vitis itself.
Thank you in advance! In Matlab I have generated C code (.c/.h files) from a Matlab function using codegen from Matlab Coder.
I call this function in a while loop on an ARM quad-core Cortex A53 using AMD Vitis.
Before calling this function I use scanf/printf to get user input and to print to the serial monitor. However, scanf/printf only work once in the 1st iteration (before calling the function) and not in the 2nd iteration or later (after calling the function).
Is this a common problem and has anyone encountered this problem before?
I think, but am not sure, that the problem is in the generated C code and not in Vitis itself.
Thank you in advance! matlab coder, code generation MATLAB Answers — New Questions
Unexpected behavior of -nouserjavapath in MATLAB R2025b compared to R2022b
Hello everyone,
I recently upgraded from MATLAB R2022b to MATLAB R2025b and noticed a change in how MATLAB handles the -nouserjavapath startup option.
I have a javaclasspath.txt file in my MATLAB prefdir, where I define several custom JAR file locations. Normally, when MATLAB starts, these JARs are correctly loaded into the static Java class path (visible via javaclasspath(‘-static’)).
In some situations, however, I want to start MATLAB without loading my custom JARs. In R2022b, starting MATLAB with:
matlab -nouserjavapath
correctly ignored the javaclasspath.txt, and my custom JARs did not appear in the static Java class path.
But in R2025b, this no longer works. Even when starting with -nouserjavapath, MATLAB still loads the JARs defined in javaclasspath.txt.
Has something changed in MATLAB R2025b regarding how the -nouserjavapath option is handled?
Is this expected behavior, a known change, or possibly a bug?
Thank you!Hello everyone,
I recently upgraded from MATLAB R2022b to MATLAB R2025b and noticed a change in how MATLAB handles the -nouserjavapath startup option.
I have a javaclasspath.txt file in my MATLAB prefdir, where I define several custom JAR file locations. Normally, when MATLAB starts, these JARs are correctly loaded into the static Java class path (visible via javaclasspath(‘-static’)).
In some situations, however, I want to start MATLAB without loading my custom JARs. In R2022b, starting MATLAB with:
matlab -nouserjavapath
correctly ignored the javaclasspath.txt, and my custom JARs did not appear in the static Java class path.
But in R2025b, this no longer works. Even when starting with -nouserjavapath, MATLAB still loads the JARs defined in javaclasspath.txt.
Has something changed in MATLAB R2025b regarding how the -nouserjavapath option is handled?
Is this expected behavior, a known change, or possibly a bug?
Thank you! Hello everyone,
I recently upgraded from MATLAB R2022b to MATLAB R2025b and noticed a change in how MATLAB handles the -nouserjavapath startup option.
I have a javaclasspath.txt file in my MATLAB prefdir, where I define several custom JAR file locations. Normally, when MATLAB starts, these JARs are correctly loaded into the static Java class path (visible via javaclasspath(‘-static’)).
In some situations, however, I want to start MATLAB without loading my custom JARs. In R2022b, starting MATLAB with:
matlab -nouserjavapath
correctly ignored the javaclasspath.txt, and my custom JARs did not appear in the static Java class path.
But in R2025b, this no longer works. Even when starting with -nouserjavapath, MATLAB still loads the JARs defined in javaclasspath.txt.
Has something changed in MATLAB R2025b regarding how the -nouserjavapath option is handled?
Is this expected behavior, a known change, or possibly a bug?
Thank you! matlab 2025b, matlab 2022b, startup option, -nouserjavapath MATLAB Answers — New Questions
fprintf not printing to command window when asking for input.
Hello. I am working on a Jukebox to play a song that corrisponds with set number (this part is not the issue I am just trying to provide some context).
When the code is run I would like the Opening menu to appear in the command window so the user can see the song choices before being prompted to enter an input. The problem is that when I run the code it does not print any of my text and just waits for an input. I think it has something to do with the fact that other than declaring some variables, there is nothing happening before the first fprintf. I am not getting any error or warning messages on my end.
Is this a quirk of using the online version? I am using the online verison of MATlab because I am having techinal issues with installing the desktop version.
(This is not all of my code, I chose to only share what is relevent to my issue)
clear
clc
close all
%% Declarations
rate = 32768; % sampling rate
songs = 1:9;
octave = 0;
speed = 0;
% Opening menu. Give list of options
fprintf([‘Welcome to Jukebox.n——– SONG MENU ——–n 1 |’…
‘ Bohemian Rhapsody n 2 | ‘ …
‘Dies Irae n 3 | Entry Into Valhalla n 4 | Fur Elise n 5 | ‘ …
‘Game of Thrones Theme n 6 | He”s a Pirate n 7 | Megalovania ‘ …
‘Long n 8 | Paint it Black n’])
% Prompt user for selection, and check validity of choice
songNum = input([‘Enter the number of the song you wish to play –> n’]);
while songNum < 0 || songNum > 9 || mod(songNum,1) ~= 0
songNum = input(‘Try again –> ‘);
endHello. I am working on a Jukebox to play a song that corrisponds with set number (this part is not the issue I am just trying to provide some context).
When the code is run I would like the Opening menu to appear in the command window so the user can see the song choices before being prompted to enter an input. The problem is that when I run the code it does not print any of my text and just waits for an input. I think it has something to do with the fact that other than declaring some variables, there is nothing happening before the first fprintf. I am not getting any error or warning messages on my end.
Is this a quirk of using the online version? I am using the online verison of MATlab because I am having techinal issues with installing the desktop version.
(This is not all of my code, I chose to only share what is relevent to my issue)
clear
clc
close all
%% Declarations
rate = 32768; % sampling rate
songs = 1:9;
octave = 0;
speed = 0;
% Opening menu. Give list of options
fprintf([‘Welcome to Jukebox.n——– SONG MENU ——–n 1 |’…
‘ Bohemian Rhapsody n 2 | ‘ …
‘Dies Irae n 3 | Entry Into Valhalla n 4 | Fur Elise n 5 | ‘ …
‘Game of Thrones Theme n 6 | He”s a Pirate n 7 | Megalovania ‘ …
‘Long n 8 | Paint it Black n’])
% Prompt user for selection, and check validity of choice
songNum = input([‘Enter the number of the song you wish to play –> n’]);
while songNum < 0 || songNum > 9 || mod(songNum,1) ~= 0
songNum = input(‘Try again –> ‘);
end Hello. I am working on a Jukebox to play a song that corrisponds with set number (this part is not the issue I am just trying to provide some context).
When the code is run I would like the Opening menu to appear in the command window so the user can see the song choices before being prompted to enter an input. The problem is that when I run the code it does not print any of my text and just waits for an input. I think it has something to do with the fact that other than declaring some variables, there is nothing happening before the first fprintf. I am not getting any error or warning messages on my end.
Is this a quirk of using the online version? I am using the online verison of MATlab because I am having techinal issues with installing the desktop version.
(This is not all of my code, I chose to only share what is relevent to my issue)
clear
clc
close all
%% Declarations
rate = 32768; % sampling rate
songs = 1:9;
octave = 0;
speed = 0;
% Opening menu. Give list of options
fprintf([‘Welcome to Jukebox.n——– SONG MENU ——–n 1 |’…
‘ Bohemian Rhapsody n 2 | ‘ …
‘Dies Irae n 3 | Entry Into Valhalla n 4 | Fur Elise n 5 | ‘ …
‘Game of Thrones Theme n 6 | He”s a Pirate n 7 | Megalovania ‘ …
‘Long n 8 | Paint it Black n’])
% Prompt user for selection, and check validity of choice
songNum = input([‘Enter the number of the song you wish to play –> n’]);
while songNum < 0 || songNum > 9 || mod(songNum,1) ~= 0
songNum = input(‘Try again –> ‘);
end fprintf, input, matlab MATLAB Answers — New Questions
The fourier series coefficient phase
I am trying to get the x[n] from fourier coefficients, then I used the fft to find the coefficients of my x[n] and compare it with the prompt. So Here is the code
N = 8; % the period
figure;
k = -4:3; % the index for fourier transform
a_k = [0,0,1,1,1,1,1,0]; % fourier series
subplot(2,2,1);
stem(k,abs(a_k)); % plot the magnitude of the fourier coefficient
xlabel(‘k’); ylabel(‘|a_k|’); title(‘Magnitude of the Fourier Series Coefficient Directly From Prompt’); %xlabel tilte and ylabel
subplot(2,2,3);
stem(k,angle(a_k)); % plot the phase of the fourier coefficient
xlabel(‘k’); ylabel(‘phase of a_k’); title(‘Phase of the Fourier Series Coefficient Directly Prompt’);%xlabel title and ylabel
x = zeros(1,N);
n = -4:3; % the n matrix
w = 2*pi/N; % omega
A = [1,2,2,0,0,0,0,0]; % the cos wave amplitude
phi = [0,0,0,0,0,0,0,0]; % the phase
for i = 1:N
x = x+A(i)*cos((i-1)*w*n+phi(i));
end
ak_re = fft(fftshift(x)); % the coefficients
ak_shifted = fftshift(ak_re); % shifted version
subplot(2,2,2);
stem(k,abs(ak_shifted)/N);% stem plot
xlabel(‘k’); ylabel(‘|a_k|’); title(‘Magnitude of the Fourier Series Coefficient by FFT’); %xlabel tilte and ylabel
subplot(2,2,4);
stem(k,angle(ak_shifted));% stem plot
xlabel(‘k’); ylabel(‘phase of a_k’); title(‘Phase of the Fourier Series Coefficient by FFT’);%xlabel title and ylabel
x_re = N*fftshift(ifft(ifftshift(a_k))); % Rebuilt x[n]
figure;
subplot(1,2,1);
stem(n,x_re); % plot the original graph
xlabel(‘n’); ylabel(‘x[n]’); title(‘Plot of x[n] Rebuilt from Coefficients’); %xlabel tilte and ylabel
subplot(1,2,2);
stem(n,x); % stem plot
xlabel(‘n’); % xlabel of the x[n]
ylabel(‘x[n]’); % ylabel
title(‘Plot of x[n] Directly from Expression’); % title
I find out that x[n] plots are same, but a_k plots are a little bit off on phase plots. Apparently the Phase of the Fourier Series Coefficient by FFT is not equal to the original phase of the coefficients by prompt. They are like half periods off. So I tried to use fftshift, but it did not help. So please let me know what is wrong here.I am trying to get the x[n] from fourier coefficients, then I used the fft to find the coefficients of my x[n] and compare it with the prompt. So Here is the code
N = 8; % the period
figure;
k = -4:3; % the index for fourier transform
a_k = [0,0,1,1,1,1,1,0]; % fourier series
subplot(2,2,1);
stem(k,abs(a_k)); % plot the magnitude of the fourier coefficient
xlabel(‘k’); ylabel(‘|a_k|’); title(‘Magnitude of the Fourier Series Coefficient Directly From Prompt’); %xlabel tilte and ylabel
subplot(2,2,3);
stem(k,angle(a_k)); % plot the phase of the fourier coefficient
xlabel(‘k’); ylabel(‘phase of a_k’); title(‘Phase of the Fourier Series Coefficient Directly Prompt’);%xlabel title and ylabel
x = zeros(1,N);
n = -4:3; % the n matrix
w = 2*pi/N; % omega
A = [1,2,2,0,0,0,0,0]; % the cos wave amplitude
phi = [0,0,0,0,0,0,0,0]; % the phase
for i = 1:N
x = x+A(i)*cos((i-1)*w*n+phi(i));
end
ak_re = fft(fftshift(x)); % the coefficients
ak_shifted = fftshift(ak_re); % shifted version
subplot(2,2,2);
stem(k,abs(ak_shifted)/N);% stem plot
xlabel(‘k’); ylabel(‘|a_k|’); title(‘Magnitude of the Fourier Series Coefficient by FFT’); %xlabel tilte and ylabel
subplot(2,2,4);
stem(k,angle(ak_shifted));% stem plot
xlabel(‘k’); ylabel(‘phase of a_k’); title(‘Phase of the Fourier Series Coefficient by FFT’);%xlabel title and ylabel
x_re = N*fftshift(ifft(ifftshift(a_k))); % Rebuilt x[n]
figure;
subplot(1,2,1);
stem(n,x_re); % plot the original graph
xlabel(‘n’); ylabel(‘x[n]’); title(‘Plot of x[n] Rebuilt from Coefficients’); %xlabel tilte and ylabel
subplot(1,2,2);
stem(n,x); % stem plot
xlabel(‘n’); % xlabel of the x[n]
ylabel(‘x[n]’); % ylabel
title(‘Plot of x[n] Directly from Expression’); % title
I find out that x[n] plots are same, but a_k plots are a little bit off on phase plots. Apparently the Phase of the Fourier Series Coefficient by FFT is not equal to the original phase of the coefficients by prompt. They are like half periods off. So I tried to use fftshift, but it did not help. So please let me know what is wrong here. I am trying to get the x[n] from fourier coefficients, then I used the fft to find the coefficients of my x[n] and compare it with the prompt. So Here is the code
N = 8; % the period
figure;
k = -4:3; % the index for fourier transform
a_k = [0,0,1,1,1,1,1,0]; % fourier series
subplot(2,2,1);
stem(k,abs(a_k)); % plot the magnitude of the fourier coefficient
xlabel(‘k’); ylabel(‘|a_k|’); title(‘Magnitude of the Fourier Series Coefficient Directly From Prompt’); %xlabel tilte and ylabel
subplot(2,2,3);
stem(k,angle(a_k)); % plot the phase of the fourier coefficient
xlabel(‘k’); ylabel(‘phase of a_k’); title(‘Phase of the Fourier Series Coefficient Directly Prompt’);%xlabel title and ylabel
x = zeros(1,N);
n = -4:3; % the n matrix
w = 2*pi/N; % omega
A = [1,2,2,0,0,0,0,0]; % the cos wave amplitude
phi = [0,0,0,0,0,0,0,0]; % the phase
for i = 1:N
x = x+A(i)*cos((i-1)*w*n+phi(i));
end
ak_re = fft(fftshift(x)); % the coefficients
ak_shifted = fftshift(ak_re); % shifted version
subplot(2,2,2);
stem(k,abs(ak_shifted)/N);% stem plot
xlabel(‘k’); ylabel(‘|a_k|’); title(‘Magnitude of the Fourier Series Coefficient by FFT’); %xlabel tilte and ylabel
subplot(2,2,4);
stem(k,angle(ak_shifted));% stem plot
xlabel(‘k’); ylabel(‘phase of a_k’); title(‘Phase of the Fourier Series Coefficient by FFT’);%xlabel title and ylabel
x_re = N*fftshift(ifft(ifftshift(a_k))); % Rebuilt x[n]
figure;
subplot(1,2,1);
stem(n,x_re); % plot the original graph
xlabel(‘n’); ylabel(‘x[n]’); title(‘Plot of x[n] Rebuilt from Coefficients’); %xlabel tilte and ylabel
subplot(1,2,2);
stem(n,x); % stem plot
xlabel(‘n’); % xlabel of the x[n]
ylabel(‘x[n]’); % ylabel
title(‘Plot of x[n] Directly from Expression’); % title
I find out that x[n] plots are same, but a_k plots are a little bit off on phase plots. Apparently the Phase of the Fourier Series Coefficient by FFT is not equal to the original phase of the coefficients by prompt. They are like half periods off. So I tried to use fftshift, but it did not help. So please let me know what is wrong here. matlab, fft, ifft, fftshift MATLAB Answers — New Questions
How to load data from Octave?
I have a .M file from Octave that I want to run in MATLAB, but I obtain an error. Here is the content of .M file (it’s just one line):
load "Slovenia_centered.mat"
And here is the error:
Error using load
Unable to read file ‘"Slovenia_centered.mat"’: Invalid argument.
Error in
Slovenia_centered (line 1)
load "Slovenia_centered.mat"
^^^^I have a .M file from Octave that I want to run in MATLAB, but I obtain an error. Here is the content of .M file (it’s just one line):
load "Slovenia_centered.mat"
And here is the error:
Error using load
Unable to read file ‘"Slovenia_centered.mat"’: Invalid argument.
Error in
Slovenia_centered (line 1)
load "Slovenia_centered.mat"
^^^^ I have a .M file from Octave that I want to run in MATLAB, but I obtain an error. Here is the content of .M file (it’s just one line):
load "Slovenia_centered.mat"
And here is the error:
Error using load
Unable to read file ‘"Slovenia_centered.mat"’: Invalid argument.
Error in
Slovenia_centered (line 1)
load "Slovenia_centered.mat"
^^^^ load MATLAB Answers — New Questions
What are the Differences between Simulink “Powertrain blockset” and “Simscape Driveline” in the case of developing a Hybrid Electric Vehicle?
Hello all. I am working on developing Energy Management Strategies for Hybrid Electric Vehicles using MATLAB and Simulink. I am now in the modelling phase and am quite stuck and confused over which approach to take. Should I develop the powertrain components in Simulink using "MATLAB FCN" blocks, or should I use Simulink libraries? If the latter, which library should I choose? Powertrain Blockset or Simscape Driveline? Which is more suited for my application? Pros and cons for both? Thanks for any help.Hello all. I am working on developing Energy Management Strategies for Hybrid Electric Vehicles using MATLAB and Simulink. I am now in the modelling phase and am quite stuck and confused over which approach to take. Should I develop the powertrain components in Simulink using "MATLAB FCN" blocks, or should I use Simulink libraries? If the latter, which library should I choose? Powertrain Blockset or Simscape Driveline? Which is more suited for my application? Pros and cons for both? Thanks for any help. Hello all. I am working on developing Energy Management Strategies for Hybrid Electric Vehicles using MATLAB and Simulink. I am now in the modelling phase and am quite stuck and confused over which approach to take. Should I develop the powertrain components in Simulink using "MATLAB FCN" blocks, or should I use Simulink libraries? If the latter, which library should I choose? Powertrain Blockset or Simscape Driveline? Which is more suited for my application? Pros and cons for both? Thanks for any help. simulink, hev, driveline, powertrainblockset MATLAB Answers — New Questions
Seeking advice on batch processing for opacity masking in ARK(Auto-Refractor Keratometer) retroillumination images (500+ images)
Hello everyone,
I am a graduate student and a relatively new user of MATLAB. I am currently working on a research project involving the analysis of ARK (Auto-Refractor Keratometer) retroillumination images to study cataracts.
I have successfully completed the first step, which is segmenting the pupil ROI (mask) from the anterior segment images using the Segment Anything Model (SAM).
Now, I am facing a challenge: I need to precisely mask the opacities (cloudy areas) within the identified pupil region. While I can perform this task for a single image using SAM, I have a dataset of approximately 500 images, making individual manual processing impractical.
I am looking for guidance on how to automate this process in MATLAB. Specifically:
Are there recommended image processing techniques (e.g., adaptive thresholding, texture analysis, or morphological operations) that work well for identifying cataract opacities within a pupil mask?
Is there a way to batch-process these 500 images efficiently while maintaining high precision?
Are there any existing File Exchange entries or toolboxes you would recommend for this type of medical image segmentation?
I would greatly appreciate any advice, code snippets, or references to help me move forward with my research.
Thank you in advance for your help!
Best regards,Hello everyone,
I am a graduate student and a relatively new user of MATLAB. I am currently working on a research project involving the analysis of ARK (Auto-Refractor Keratometer) retroillumination images to study cataracts.
I have successfully completed the first step, which is segmenting the pupil ROI (mask) from the anterior segment images using the Segment Anything Model (SAM).
Now, I am facing a challenge: I need to precisely mask the opacities (cloudy areas) within the identified pupil region. While I can perform this task for a single image using SAM, I have a dataset of approximately 500 images, making individual manual processing impractical.
I am looking for guidance on how to automate this process in MATLAB. Specifically:
Are there recommended image processing techniques (e.g., adaptive thresholding, texture analysis, or morphological operations) that work well for identifying cataract opacities within a pupil mask?
Is there a way to batch-process these 500 images efficiently while maintaining high precision?
Are there any existing File Exchange entries or toolboxes you would recommend for this type of medical image segmentation?
I would greatly appreciate any advice, code snippets, or references to help me move forward with my research.
Thank you in advance for your help!
Best regards, Hello everyone,
I am a graduate student and a relatively new user of MATLAB. I am currently working on a research project involving the analysis of ARK (Auto-Refractor Keratometer) retroillumination images to study cataracts.
I have successfully completed the first step, which is segmenting the pupil ROI (mask) from the anterior segment images using the Segment Anything Model (SAM).
Now, I am facing a challenge: I need to precisely mask the opacities (cloudy areas) within the identified pupil region. While I can perform this task for a single image using SAM, I have a dataset of approximately 500 images, making individual manual processing impractical.
I am looking for guidance on how to automate this process in MATLAB. Specifically:
Are there recommended image processing techniques (e.g., adaptive thresholding, texture analysis, or morphological operations) that work well for identifying cataract opacities within a pupil mask?
Is there a way to batch-process these 500 images efficiently while maintaining high precision?
Are there any existing File Exchange entries or toolboxes you would recommend for this type of medical image segmentation?
I would greatly appreciate any advice, code snippets, or references to help me move forward with my research.
Thank you in advance for your help!
Best regards, image processing, masking, image processing toolbox MATLAB Answers — New Questions
Deconvolution using FFT – a classical problem
Hello friends, I am new to signal processing and I am trying to achive deconvolution using FFT. I have an input step function u(t) applied to an impulse response given by . The output function is . I am trying to convolve g and u to get y as well as deconvolve y and g to get u. However, I quite cannot get the right answers. I understand that the deconvolution process is ill-posed and I have to use some kind of normalization process but I am lost. I also apply zero padding to twice the length of the input signals. Any sort of guidance will be appreciated.
After using deconvolution in the fourier domain:
Y = fft(y)
G = fft(g)
X = Y./G
x = ifft(X)
I am getting an output shown below:
Which is not the expected outcome. Can someone shead light on what is happening here? Thank you.Hello friends, I am new to signal processing and I am trying to achive deconvolution using FFT. I have an input step function u(t) applied to an impulse response given by . The output function is . I am trying to convolve g and u to get y as well as deconvolve y and g to get u. However, I quite cannot get the right answers. I understand that the deconvolution process is ill-posed and I have to use some kind of normalization process but I am lost. I also apply zero padding to twice the length of the input signals. Any sort of guidance will be appreciated.
After using deconvolution in the fourier domain:
Y = fft(y)
G = fft(g)
X = Y./G
x = ifft(X)
I am getting an output shown below:
Which is not the expected outcome. Can someone shead light on what is happening here? Thank you. Hello friends, I am new to signal processing and I am trying to achive deconvolution using FFT. I have an input step function u(t) applied to an impulse response given by . The output function is . I am trying to convolve g and u to get y as well as deconvolve y and g to get u. However, I quite cannot get the right answers. I understand that the deconvolution process is ill-posed and I have to use some kind of normalization process but I am lost. I also apply zero padding to twice the length of the input signals. Any sort of guidance will be appreciated.
After using deconvolution in the fourier domain:
Y = fft(y)
G = fft(g)
X = Y./G
x = ifft(X)
I am getting an output shown below:
Which is not the expected outcome. Can someone shead light on what is happening here? Thank you. deconvolution, fft, inverse problem MATLAB Answers — New Questions
How to do Multichannel statistical analysis?
I just need an example:
%% Load data
% Lab says use readtable, then convert to array
T = readtable("Section2.csv");
data = table2array(T);
% Assumption: column 1 is time/index, columns 2:11 are the 10 subjects
X = data(:,2:11); % Nx10 matrix (each column = one subject)
%% =========================
% [3.2] Central tendency + dispersion for each subject
% mean, median, range, std (one value per subject/column)
% =========================
mean_data = mean(X, ‘omitnan’); % 1×10
median_data = median(X, ‘omitnan’); % 1×10
% Use max-min for range (robust if MATLAB "range" gives issues)
range_data = max(X, [], 1) – min(X, [], 1); % 1×10
std_data = std(X, 0, ‘omitnan’); % 1×10 (0 = sample std)
%% =========================
% [3.2] Find which subject has max/min for each metric
% Lab asks to do this by code (not by looking)
% =========================
[max_mean, subj_max_mean] = max(mean_data);
[min_mean, subj_min_mean] = min(mean_data);
[max_median, subj_max_median] = max(median_data);
[min_median, subj_min_median] = min(median_data);
[max_range, subj_max_range] = max(range_data);
[min_range, subj_min_range] = min(range_data);
[max_std, subj_max_std] = max(std_data);
[min_std, subj_min_std] = min(std_data);
% Display summary
fprintf(‘n=== Subject Extremes (Subjects 1-10) ===n’);
fprintf(‘Mean : max = %.2f (Subject %d), min = %.2f (Subject %d)n’, …
max_mean, subj_max_mean, min_mean, subj_min_mean);
fprintf(‘Median : max = %.2f (Subject %d), min = %.2f (Subject %d)n’, …
max_median, subj_max_median, min_median, subj_min_median);
fprintf(‘Range : max = %.2f (Subject %d), min = %.2f (Subject %d)n’, …
max_range, subj_max_range, min_range, subj_min_range);
fprintf(‘Std Dev: max = %.2f (Subject %d), min = %.2f (Subject %d)n’, …
max_std, subj_max_std, min_std, subj_min_std);
%% =========================
% [3.2] Time spent > (mean + 20 bpm), in HOURS
% Lab says each row = 5 seconds
% =========================
function hours = time_over(colVec, meanVal)
% colVec = one subject’s HR time series (Nx1)
% meanVal = mean HR for that subject
count = sum(colVec > (meanVal + 20)); % number of samples above threshold
hours = (count * 5) / 3600; % 5 s/sample -> hours
end
% Compute for all 10 subjects
hours_over = zeros(1,10);
for s = 1:10
hours_over(s) = time_over(X(:,s), mean_data(s));
end
% Optional: display results neatly
fprintf(‘n=== Time above (mean + 20 bpm) ===n’);
for s = 1:10
fprintf(‘Subject %d: %.3f hoursn’, s, hours_over(s));
end
%% Optional: put everything into a table (nice for report/checking)
subject_id = (1:10)’;
resultsTbl = table(subject_id, mean_data’, median_data’, range_data’, std_data’, hours_over’, …
‘VariableNames’, {‘Subject’,’MeanHR’,’MedianHR’,’RangeHR’,’StdHR’,’HoursAboveMeanPlus20′});
disp(resultsTbl);I just need an example:
%% Load data
% Lab says use readtable, then convert to array
T = readtable("Section2.csv");
data = table2array(T);
% Assumption: column 1 is time/index, columns 2:11 are the 10 subjects
X = data(:,2:11); % Nx10 matrix (each column = one subject)
%% =========================
% [3.2] Central tendency + dispersion for each subject
% mean, median, range, std (one value per subject/column)
% =========================
mean_data = mean(X, ‘omitnan’); % 1×10
median_data = median(X, ‘omitnan’); % 1×10
% Use max-min for range (robust if MATLAB "range" gives issues)
range_data = max(X, [], 1) – min(X, [], 1); % 1×10
std_data = std(X, 0, ‘omitnan’); % 1×10 (0 = sample std)
%% =========================
% [3.2] Find which subject has max/min for each metric
% Lab asks to do this by code (not by looking)
% =========================
[max_mean, subj_max_mean] = max(mean_data);
[min_mean, subj_min_mean] = min(mean_data);
[max_median, subj_max_median] = max(median_data);
[min_median, subj_min_median] = min(median_data);
[max_range, subj_max_range] = max(range_data);
[min_range, subj_min_range] = min(range_data);
[max_std, subj_max_std] = max(std_data);
[min_std, subj_min_std] = min(std_data);
% Display summary
fprintf(‘n=== Subject Extremes (Subjects 1-10) ===n’);
fprintf(‘Mean : max = %.2f (Subject %d), min = %.2f (Subject %d)n’, …
max_mean, subj_max_mean, min_mean, subj_min_mean);
fprintf(‘Median : max = %.2f (Subject %d), min = %.2f (Subject %d)n’, …
max_median, subj_max_median, min_median, subj_min_median);
fprintf(‘Range : max = %.2f (Subject %d), min = %.2f (Subject %d)n’, …
max_range, subj_max_range, min_range, subj_min_range);
fprintf(‘Std Dev: max = %.2f (Subject %d), min = %.2f (Subject %d)n’, …
max_std, subj_max_std, min_std, subj_min_std);
%% =========================
% [3.2] Time spent > (mean + 20 bpm), in HOURS
% Lab says each row = 5 seconds
% =========================
function hours = time_over(colVec, meanVal)
% colVec = one subject’s HR time series (Nx1)
% meanVal = mean HR for that subject
count = sum(colVec > (meanVal + 20)); % number of samples above threshold
hours = (count * 5) / 3600; % 5 s/sample -> hours
end
% Compute for all 10 subjects
hours_over = zeros(1,10);
for s = 1:10
hours_over(s) = time_over(X(:,s), mean_data(s));
end
% Optional: display results neatly
fprintf(‘n=== Time above (mean + 20 bpm) ===n’);
for s = 1:10
fprintf(‘Subject %d: %.3f hoursn’, s, hours_over(s));
end
%% Optional: put everything into a table (nice for report/checking)
subject_id = (1:10)’;
resultsTbl = table(subject_id, mean_data’, median_data’, range_data’, std_data’, hours_over’, …
‘VariableNames’, {‘Subject’,’MeanHR’,’MedianHR’,’RangeHR’,’StdHR’,’HoursAboveMeanPlus20′});
disp(resultsTbl); I just need an example:
%% Load data
% Lab says use readtable, then convert to array
T = readtable("Section2.csv");
data = table2array(T);
% Assumption: column 1 is time/index, columns 2:11 are the 10 subjects
X = data(:,2:11); % Nx10 matrix (each column = one subject)
%% =========================
% [3.2] Central tendency + dispersion for each subject
% mean, median, range, std (one value per subject/column)
% =========================
mean_data = mean(X, ‘omitnan’); % 1×10
median_data = median(X, ‘omitnan’); % 1×10
% Use max-min for range (robust if MATLAB "range" gives issues)
range_data = max(X, [], 1) – min(X, [], 1); % 1×10
std_data = std(X, 0, ‘omitnan’); % 1×10 (0 = sample std)
%% =========================
% [3.2] Find which subject has max/min for each metric
% Lab asks to do this by code (not by looking)
% =========================
[max_mean, subj_max_mean] = max(mean_data);
[min_mean, subj_min_mean] = min(mean_data);
[max_median, subj_max_median] = max(median_data);
[min_median, subj_min_median] = min(median_data);
[max_range, subj_max_range] = max(range_data);
[min_range, subj_min_range] = min(range_data);
[max_std, subj_max_std] = max(std_data);
[min_std, subj_min_std] = min(std_data);
% Display summary
fprintf(‘n=== Subject Extremes (Subjects 1-10) ===n’);
fprintf(‘Mean : max = %.2f (Subject %d), min = %.2f (Subject %d)n’, …
max_mean, subj_max_mean, min_mean, subj_min_mean);
fprintf(‘Median : max = %.2f (Subject %d), min = %.2f (Subject %d)n’, …
max_median, subj_max_median, min_median, subj_min_median);
fprintf(‘Range : max = %.2f (Subject %d), min = %.2f (Subject %d)n’, …
max_range, subj_max_range, min_range, subj_min_range);
fprintf(‘Std Dev: max = %.2f (Subject %d), min = %.2f (Subject %d)n’, …
max_std, subj_max_std, min_std, subj_min_std);
%% =========================
% [3.2] Time spent > (mean + 20 bpm), in HOURS
% Lab says each row = 5 seconds
% =========================
function hours = time_over(colVec, meanVal)
% colVec = one subject’s HR time series (Nx1)
% meanVal = mean HR for that subject
count = sum(colVec > (meanVal + 20)); % number of samples above threshold
hours = (count * 5) / 3600; % 5 s/sample -> hours
end
% Compute for all 10 subjects
hours_over = zeros(1,10);
for s = 1:10
hours_over(s) = time_over(X(:,s), mean_data(s));
end
% Optional: display results neatly
fprintf(‘n=== Time above (mean + 20 bpm) ===n’);
for s = 1:10
fprintf(‘Subject %d: %.3f hoursn’, s, hours_over(s));
end
%% Optional: put everything into a table (nice for report/checking)
subject_id = (1:10)’;
resultsTbl = table(subject_id, mean_data’, median_data’, range_data’, std_data’, hours_over’, …
‘VariableNames’, {‘Subject’,’MeanHR’,’MedianHR’,’RangeHR’,’StdHR’,’HoursAboveMeanPlus20′});
disp(resultsTbl); multichannel statistical analysis MATLAB Answers — New Questions









