Author: PuTI
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
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
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
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
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
Microsoft Sovereign Cloud adds governance, productivity and support for large AI models securely running even when completely disconnected
As digital sovereignty becomes a strategic requirement, organizations are rethinking how they deploy critical infrastructure and AI capabilities under tighter regulatory expectations and higher risk conditions. Microsoft’s approach to sovereignty is grounded in enabling enterprises, public sectors and regulated industries to participate in the digital economy securely, independently and on their own terms. The Microsoft Sovereign Cloud brings together productivity, security and cloud workloads to span both public and private environments. Customers can choose the right control posture for each workload, through a continuum of sovereign options protecting against fragmenting their architecture or increasing operational risk. Trust is built on confidence: confidence that data stays protected, controls are enforceable and operations can continue under real-world conditions.
To support these confidential environments, Microsoft offers full stack capabilities that support customers across connected, intermittently connected and fully disconnected modes. Today’s expansion of capabilities includes three major updates:
- Azure Local disconnected operations (now available) – Organizations can now run mission-critical infrastructure with Azure governance and policy control, with no cloud connectivity, optimizing continuity for sovereign, classified or isolated environments.
- Microsoft 365 Local disconnected (now available) – Core productivity workloads, Exchange Server, SharePoint Server and Skype for Business Server can run fully inside the customer’s sovereign operational boundary on Azure Local, keeping teams productive even when disconnected from the cloud.
- Foundry Local adds modern infrastructure capabilities and support for large AI models – Organizations can now bring large AI models into fully disconnected, sovereign environments with Foundry Local. Using modern infrastructure from partners like NVIDIA, customers with sovereign needs will now be able to run multimodal models locally on their own hardware, inside strict sovereign boundaries enabling powerful, local AI inferencing in fully disconnected environments.

This delivers a truly localized full stack experience built on Azure Local infrastructure and Microsoft 365 Local workloads, designed to stay resilient across any connectivity condition, with large models being part of Foundry Local extending the stack to run advanced multimodal models locally, securely, even when fully disconnected. Customers can now help maintain uninterrupted operations, keep mission critical workloads protected and apply consistent governance and policy enforcement, while keeping data, identities and operations within their sovereign boundaries.
Azure Local runs critical infrastructure locally, even when disconnected
For workloads with specialized requirements, Azure Local provides the on-premises foundation with consistent Azure governance and policy controls. With Azure Local disconnected operations, management, policy and workload execution stay within the customer-operated environments, so services continue running securely even when environments must be isolated or connectivity is not available. Using familiar Azure experiences and consistent policies, organizations can deploy and govern workloads locally without depending on continuous connection to public cloud services. Azure Local is designed to scale with mission-critical needs from smaller deployments to larger footprints that support data-intensive and AI-driven workloads. Customers can start fast, expand over time and maintain a unified operational model, all within their sovereign boundary.
Operating in disconnected environments surfaces constraints that go beyond traditional cloud assumptions: External dependencies may be unacceptable, connectivity may be intentionally restricted and operational continuity is a business imperative.
“The availability of Azure Local disconnected operations represents a breakthrough for organizations that need control over their data without sacrificing the power of the Microsoft Cloud. For Luxembourg, where digital sovereignty is not just a principle but a strategic necessity, this model offers the resilience, autonomy and trust our market expects. By combining Microsoft’s technological leadership with Proximus NXT’s sovereign cloud expertise, we are enabling our customers to innovate confidently — even in fully disconnected mode,” said Gerard Hoffmann, CEO Proximus Luxembourg.
Microsoft 365 Local keeps productivity and collaboration available in fully disconnected environments
As sovereign environments move into disconnected environments, keeping people productive becomes just as critical as keeping infrastructure online. Building on more than a decade of delivering and supporting these services, Microsoft 365 Local disconnected brings that continuity to the productivity layer, delivering Microsoft’s core server workloads — Exchange Server, SharePoint Server and Skype for Business Server supported through at least 2035 — directly into the customer’s sovereign private cloud.
With Microsoft 365 Local, teams can communicate, share information and collaborate securely within the same controlled boundary as their infrastructure and AI workloads. Everything runs locally, under customer-owned policies, with full control of data resiliency, access and compliance. By operating with Azure-consistent management and governance, customers get the productivity experience they rely on, designed to stay resilient and secure even when offline.
Bringing large models and modern infrastructure to Foundry Local
With the availability of larger models and modern infrastructure as part of the Foundry Local portfolio, Microsoft is enabling customers with highly secure environments the ability to run multimodal, large models directly inside their sovereign private cloud environments. This brings the richness of Microsoft’s enterprise AI capabilities to on-premises systems, complete with local inferencing and APIs that operate completely within customer-controlled data boundaries.
Expanding beyond small models, the integration of Foundry Local with Azure Local is specifically designed to support large-scale models utilizing the latest GPUs from partners such as NVIDIA. Microsoft will provide comprehensive support for deployments, updates and operational health. Even as inferencing demands increase over time, customers retain complete control over their data and hardware.
Choice and control without added complexity
Customers facing strict sovereignty and regulatory requirements are clear that a fully disconnected sovereign private cloud is a key business need. Microsoft Sovereign Private Cloud is designed to meet these needs head-on, enabling secure, compliant operations even in environments with no external connectivity. At the same time, we recognize that disconnected environments are not one-size-fits-all; some customers operate across connected, hybrid and disconnected modes based on mission, risk and regulation. Our approach helps customers to meet strict sovereign requirements in fully disconnected scenarios without compromising simplicity, while retaining flexibility where connectivity is possible. Together, Azure Local disconnected operations, Microsoft 365 Local and Foundry Local help organizations choose where workloads run and how environments are managed, while standardizing governance and operational practices across connected and disconnected deployments.
Get started
- Azure Local disconnected operations and Microsoft 365 Local disconnected are now available worldwide, and large models on Foundry Local are available to qualified customers.
- Explore the Microsoft Sovereign Cloud
- Learn more about Azure Local disconnected operations
Douglas Phillips leads global engineering efforts for Microsoft’s specialized, sovereign, and private clouds. He is responsible for Microsoft’s global strategy, products and operations that bring Microsoft’s industry-leading solutions, including Azure, our adaptive cloud portfolio and Microsoft 365 collaboration suite, to customers with additional sovereignty, security, edge and compliance requirements.
The post Microsoft Sovereign Cloud adds governance, productivity and support for large AI models securely running even when completely disconnected appeared first on The Official Microsoft Blog.
As digital sovereignty becomes a strategic requirement, organizations are rethinking how they deploy critical infrastructure and AI capabilities under tighter regulatory expectations and higher risk conditions. Microsoft’s approach to sovereignty is grounded in enabling enterprises, public sectors and regulated industries to participate in the digital economy securely, independently and on their own terms. The Microsoft Sovereign Cloud brings together productivity, security and cloud workloads to span both…
The post Microsoft Sovereign Cloud adds governance, productivity and support for large AI models securely running even when completely disconnected appeared first on The Official Microsoft Blog.
Read More
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
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
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
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
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
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
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
Asha Sharma named EVP and CEO, Microsoft Gaming
Satya Nadella, Chairman and CEO, and members of his executive team shared the following communications with employees today.
SATYA NADELLA MESSAGE
Gaming has been part of Microsoft from the start. Flight Simulator shipped before Windows, and you can practically ray‑trace a line from DirectX in the ’90s to the accelerated‑compute era we’re in today.
As we celebrate Xbox’s 25th year, the opportunity and innovation agenda in front of us is expansive. Today we reach over 500 million monthly active users, are a top publisher across all platforms, and continue to innovate across gaming hardware, content, and community, in service of creators and players everywhere.
I am long on gaming and its role at the center of our consumer ambition, and as we look ahead, I’m excited to share that Asha Sharma will become Executive Vice President and CEO, Microsoft Gaming, reporting to me. Over the last two years at Microsoft, and previously as Chief Operating Officer at Instacart and a Vice President at Meta, Asha has helped build and scale services that reach billions of people and support thriving consumer and developer ecosystems. She brings deep experience building and growing platforms, aligning business models to long-term value, and operating at global scale, which will be critical in leading our gaming business into its next era of growth.
Matt Booty will become Executive Vice President and Chief Content Officer, reporting to Asha. Matt’s career reflects a lifelong commitment to games and to the people who make them. Under his leadership, Microsoft Gaming has grown to span nearly 40 studios across Xbox, Bethesda, Activision Blizzard, and King, which are home to beloved franchises including Halo, The Elder Scrolls, Call of Duty, World of Warcraft, Diablo, Candy Crush, and Fallout.
Together, Asha and Matt have the right combination of consumer product leadership and gaming depth to push our platform innovation and content pipeline forward. Last year, Phil Spencer made the decision to retire from the company, and since then we’ve been talking about succession planning. I want to thank Phil for his extraordinary leadership and partnership. Over 38 years at Microsoft, including 12 years leading Gaming, Phil helped transform what we do and how we do it. He expanded our reach across PC, mobile, and cloud; nearly tripled the size of the business; helped shape our strategy through the acquisitions of Activision Blizzard, ZeniMax, and Minecraft; and strengthened our culture across our studios and platforms. I’ve long admired Phil’s unwavering commitment to players, creators, and his team, and I am personally grateful for his leadership and counsel. He will continue working closely with Asha to ensure a smooth transition.
We have extraordinary creative talent across our studios and a global platform that is second to none. I’m excited for how we will capture the opportunity ahead and define what comes next, while staying grounded in what players and creators value.
Please join me in congratulating Asha and Matt on their new roles, and in thanking Phil for everything he has done for Microsoft and for our industry.
PHIL SPENCER MESSAGE
When I walked through Microsoft’s doors as an intern in June of 1988, I could never have imagined the products I’d help build, the players and customers we’d serve, or the extraordinary teams I’d be lucky enough to join. It’s been an epic ride and truly the privilege of a lifetime.
Last fall, I shared with Satya that I was thinking about stepping back and starting the next chapter of my life. From that moment, we aligned on approaching this transition with intention, ensuring stability, and strengthening the foundation we’ve built. Xbox has always been more than a business. It’s a vibrant community of players, creators, and teams who care deeply about what we build and how we build it. And it deserves a thoughtful, deliberate plan for the road ahead.
Today marks an exciting new chapter for Microsoft Gaming as Asha Sharma steps into the role of CEO, and I want to be the first to welcome her to this incredible team. Working with her over the past several months has given me tremendous confidence. She brings genuine curiosity, clarity and a deep commitment to understanding players, creators, and the decisions that shape our future. We know this is an important moment for our fans, partners, and team, and we’re committed to getting it right. I’ll remain in an advisory role through the summer to support a smooth handoff.
I’m also grateful for the strength of our studios organization. Matt Booty and our studios teams continue to build an incredible portfolio, and I have full confidence in the leadership and creative momentum across our global studios. I want to congratulate Matt on his promotion to EVP and Chief Content Officer.
As part of this transition, Sarah Bond has decided to leave Microsoft to begin a new chapter. Sarah has been instrumental during a defining period for Xbox, shaping our platform strategy, expanding Game Pass and cloud gaming, supporting new hardware launches, and guiding some of the most significant moments in our history. I’m grateful for her partnership and the impact she’s had, and I wish her the very best in what comes next.
Most of all, to everyone in Microsoft Gaming, I want to say “thank you.” I’ve learned so much from this team and community, grown alongside you, and been continually inspired by the creativity, courage, and care you bring to players, creators, and to one another every day.
I’m incredibly proud of what we’ve built together over the last 25 years, and I have complete confidence in all of you and in the opportunities ahead. I’ll be cheering you on in this next chapter as Xbox’s proudest fan and player.
Phil
XBL: P3
ASHA SHARMA MESSAGE
Dear team,
Today I begin my role as CEO of Microsoft Gaming.
I feel two things at once: humility and urgency.
Humility because this team has built something extraordinary over decades. Urgency because gaming is in a period of rapid change, and we need to move with clarity and conviction.
I am stepping into work shaped by generations of artists, engineers, designers, writers, musicians, operators and more who create worlds that have brought joy and deep personal meaning to hundreds of millions of players. The level of craft here is exceptional, and it is amplified by Xbox, which was founded in the belief that the power of games connects people and pushes the industry forward.
Thank you to Phil for his leadership, and to every studio, platform, and operations team that built this foundation. We are stewards of some of the most loved stories and characters in entertainment and bring players and creators together around the fun and community of gaming in entirely new ways.
My first job is simple: understand what makes this work and protect it.
That starts with three commitments.
First, great games.
Everything begins here. We must have great games beloved by players before we do anything. Unforgettable characters, stories that make us feel, innovative game play, and creative excellence. We will empower our studios, invest in iconic franchises, and back bold new ideas. We will take risks. We will enter new categories and markets where we can add real value, grounded in what players care about most.
I promoted Matt Booty in honor of this commitment. He understands the craft and the challenges of building great games, has led teams that deliver award-winning work, and has earned the trust of game developers across the industry.
Second, the return of Xbox.
We will recommit to our core Xbox fans and players, those who have invested with us for the past 25 years, and to the developers who build the expansive universes and experiences that are embraced by players across the world.
We will celebrate our roots with a renewed commitment to Xbox starting with console which has shaped who we are. It connects us to the players and fans who invest in Xbox, and to the developers who build ambitious experiences for it.
Gaming now lives across devices, not within the limits of any single piece of hardware. As we expand across PC, mobile, and cloud, Xbox should feel seamless, instant, and worthy of the communities we serve. We will break down barriers so developers can build once and reach players everywhere without compromise.
Third, future of play.
We are witnessing the reinvention of play.
To meet the moment, we will invent new business models and new ways to play by leaning into what we already have: iconic teams, characters, and worlds that people love. But we will not treat those worlds as static IP to milk and monetize. We will build a shared platform and tools that empower developers and players to create and share their own stories.
As monetization and AI evolve and influence this future, we will not chase short-term efficiency or flood our ecosystem with soulless AI slop. Games are and always will be art, crafted by humans, and created with the most innovative technology provided by us.
The next 25 years belong to the teams who dare to build something surprising, something no one else is willing to try, and have the patience to see it through. We have done this before, and I am here to help us do it again. I want to return to the renegade spirit that built Xbox in the first place. It will require us to relentlessly question everything, revisit processes, protect what works, and be brave enough to change what does not.
Thank you for welcoming me into this journey.
Asha
MATT BOOTY MESSAGE
I read Phil’s note with much gratitude. He has been a steady champion for game creators and our studio teams, and I’ve learned so much from his leadership over the years. All our games have benefited from his foundational support. I’m also grateful to Satya for his ongoing commitment to gaming and holding a vision of how it can connect back to the larger company.
Looking forward, I’m excited to partner with Asha as our next CEO. Our first conversations centered on her commitment to making great games and the role that plays in our overall success. She asks questions, pushes for clarity, and wants our choices grounded in player and developer needs. That mindset matters as the industry around us is changing quickly: how players engage, how games are made, and how business models and platforms evolve.
We have good reasons to believe in what’s ahead. This organization and its franchises have navigated change for decades, and our strength comes from teams who know how to adapt and keep delivering. That confidence is grounded in a strong pipeline of established franchises, new bets we believe in, and clear player demand for what we are building.
My focus is on supporting the teams and leaders we have in place and creating the conditions for them to do their best work. To be clear, there are no organizational changes underway for our studios.
Thanks for everything you do for players and for each other.
Matt
The post Asha Sharma named EVP and CEO, Microsoft Gaming appeared first on The Official Microsoft Blog.
Satya Nadella, Chairman and CEO, and members of his executive team shared the following communications with employees today. SATYA NADELLA MESSAGE Gaming has been part of Microsoft from the start. Flight Simulator shipped before Windows, and you can practically ray‑trace a line from DirectX in the ’90s to the accelerated‑compute era we’re in today. As…
The post Asha Sharma named EVP and CEO, Microsoft Gaming appeared first on The Official Microsoft Blog.
Read More









