Tag Archives: matlab
Request for MATLAB Code Review and Correction
The image contains the Transmission Line (TRL) equation. I am trying to develop a MATLAB code that matches this equation accurately. However, I need to verify that the implementation is consistent with the mathematical expression shown in the image.
Could you please review it and help ensure that the MATLAB code correctly follows the TRL equation?
Here this matlab code
clc;
clear;
% ===== Constants =====
c = 3e8; % Speed of light (m/s)
d = 2.62e-3; % Thickness in meters (example: 2.62 mm)
% ——————- Ask user to select Excel file ——————-
[filename, pathname] = uigetfile(‘*.xlsx’, ‘Select your S-parameter Excel file’);
if isequal(filename,0)
error(‘No file selected. Exiting…’);
end
filepath = fullfile(pathname, filename);
% ===== Read data from Excel =====
% Make sure your Excel file has columns: frequency(Hz), e’, e”, u’, u”
data = readmatrix(filepath); % Reads all numeric data
f = data(:,1); % Frequency in Hz
ep_real = data(:,2); % e’
ep_imag = data(:,3); % e”
mu_real = data(:,4); % u’
mu_imag = data(:,5); % u”
% ===== Complex parameters =====
eps_r = ep_real – 1i*ep_imag;
mu_r = mu_real – 1i*mu_imag;
% ===== Input impedance calculation =====
Zin = sqrt(mu_r ./ eps_r) .* tanh(-1i .* (2*pi.*f.*d./c) .* sqrt(mu_r .* eps_r));
% ===== Reflection Loss =====
RL = 20*log10(abs((Zin – 1) ./ (Zin + 1)));
% ===== Reflection coefficient =====
Gamma = abs((Zin – 1) ./ (Zin + 1));
% ===== Absorption percentage =====
Absorption = (1 – Gamma.^2) * 100;
% ===== Display results =====
Result = table(f, RL, Absorption)
% ===== Plot RL =====
figure
plot(f/1e9, RL,’LineWidth’,2)
xlabel(‘Frequency (GHz)’)
ylabel(‘Reflection Loss (dB)’)
title(‘Reflection Loss vs Frequency’)
grid onThe image contains the Transmission Line (TRL) equation. I am trying to develop a MATLAB code that matches this equation accurately. However, I need to verify that the implementation is consistent with the mathematical expression shown in the image.
Could you please review it and help ensure that the MATLAB code correctly follows the TRL equation?
Here this matlab code
clc;
clear;
% ===== Constants =====
c = 3e8; % Speed of light (m/s)
d = 2.62e-3; % Thickness in meters (example: 2.62 mm)
% ——————- Ask user to select Excel file ——————-
[filename, pathname] = uigetfile(‘*.xlsx’, ‘Select your S-parameter Excel file’);
if isequal(filename,0)
error(‘No file selected. Exiting…’);
end
filepath = fullfile(pathname, filename);
% ===== Read data from Excel =====
% Make sure your Excel file has columns: frequency(Hz), e’, e”, u’, u”
data = readmatrix(filepath); % Reads all numeric data
f = data(:,1); % Frequency in Hz
ep_real = data(:,2); % e’
ep_imag = data(:,3); % e”
mu_real = data(:,4); % u’
mu_imag = data(:,5); % u”
% ===== Complex parameters =====
eps_r = ep_real – 1i*ep_imag;
mu_r = mu_real – 1i*mu_imag;
% ===== Input impedance calculation =====
Zin = sqrt(mu_r ./ eps_r) .* tanh(-1i .* (2*pi.*f.*d./c) .* sqrt(mu_r .* eps_r));
% ===== Reflection Loss =====
RL = 20*log10(abs((Zin – 1) ./ (Zin + 1)));
% ===== Reflection coefficient =====
Gamma = abs((Zin – 1) ./ (Zin + 1));
% ===== Absorption percentage =====
Absorption = (1 – Gamma.^2) * 100;
% ===== Display results =====
Result = table(f, RL, Absorption)
% ===== Plot RL =====
figure
plot(f/1e9, RL,’LineWidth’,2)
xlabel(‘Frequency (GHz)’)
ylabel(‘Reflection Loss (dB)’)
title(‘Reflection Loss vs Frequency’)
grid on The image contains the Transmission Line (TRL) equation. I am trying to develop a MATLAB code that matches this equation accurately. However, I need to verify that the implementation is consistent with the mathematical expression shown in the image.
Could you please review it and help ensure that the MATLAB code correctly follows the TRL equation?
Here this matlab code
clc;
clear;
% ===== Constants =====
c = 3e8; % Speed of light (m/s)
d = 2.62e-3; % Thickness in meters (example: 2.62 mm)
% ——————- Ask user to select Excel file ——————-
[filename, pathname] = uigetfile(‘*.xlsx’, ‘Select your S-parameter Excel file’);
if isequal(filename,0)
error(‘No file selected. Exiting…’);
end
filepath = fullfile(pathname, filename);
% ===== Read data from Excel =====
% Make sure your Excel file has columns: frequency(Hz), e’, e”, u’, u”
data = readmatrix(filepath); % Reads all numeric data
f = data(:,1); % Frequency in Hz
ep_real = data(:,2); % e’
ep_imag = data(:,3); % e”
mu_real = data(:,4); % u’
mu_imag = data(:,5); % u”
% ===== Complex parameters =====
eps_r = ep_real – 1i*ep_imag;
mu_r = mu_real – 1i*mu_imag;
% ===== Input impedance calculation =====
Zin = sqrt(mu_r ./ eps_r) .* tanh(-1i .* (2*pi.*f.*d./c) .* sqrt(mu_r .* eps_r));
% ===== Reflection Loss =====
RL = 20*log10(abs((Zin – 1) ./ (Zin + 1)));
% ===== Reflection coefficient =====
Gamma = abs((Zin – 1) ./ (Zin + 1));
% ===== Absorption percentage =====
Absorption = (1 – Gamma.^2) * 100;
% ===== Display results =====
Result = table(f, RL, Absorption)
% ===== Plot RL =====
figure
plot(f/1e9, RL,’LineWidth’,2)
xlabel(‘Frequency (GHz)’)
ylabel(‘Reflection Loss (dB)’)
title(‘Reflection Loss vs Frequency’)
grid on transmission line theory trl equation matlab ma MATLAB Answers — New Questions
Weird Behaviour of Parallel Processing when Using BlockProc
Hello, I a trying to speed up some analysis of an image (4700 v 128 pixels) that needs breaking up into smaller regions (20×128 pixels) and for each region having a calculation done such as the standard deviation (std2)
I thought the combination of Blockproc and the parallel toolbox would be ideal for this.
However, when I run my analysis, I sometmes get a fast completion time of 0.25s, but other times I run it it can take upto 3s.
1: When I start up my matlab session, i start a parallel pool:
% For parallel Processing (init parpool here)
delete(gcp(‘nocreate’)); % but delete any that are already running
c=parcluster(‘local’);
numwks=c.NumWorkers;
ReportMessage(app,[‘Parallel processing: NumWorkers = ‘,num2str(numwks)]);
parpool(‘Processes’,numwks);
p=gcp;
conn=p.Connected;
ReportMessage(app,[‘…Connected ‘,num2str(conn)]);
2: I then run my fucntion from a push button callback.
My function first gets an image off a uiaxes, crops it and then performs the blockproc.
% Fast Analysis (SD)
tstart=tic;
ax=app.UIAxes;
IM=getimage(ax);
[sy,sx]=size(IM);
xl=5950; xr=10680; yb=0; yt=0; dx=xr-xl; % This is for image cropping
rect=[xl, yb, xr-xl,sy-yt-yb]; %[x, y, width, height]
IM2=imcrop(IM,rect);
IM=IM2-min(IM2(:)); % Background subtract
[sy,sx]=size(IM);
ColSize=20; % Number of pixels in each ROI – 20 default
nCols=floor(sx/ColSize);
RowSize = 128;
%BlockProc with Parallel
bss = [RowSize,ColSize]; % Each blockproc region
fh = @(bs) std2(bs.data); % perform this on each block
J = blockproc(IM, bss, fh,’UseParallel’,true);
sd=J’; % Column vector
ReportMessage(app,num2str(toc(tstart)));
Is there something I am doing wrong? Do I need to close and reopen the parpool everytime or something.
Also, if I want the fh function to be a functio that has more than 1 argument, how do I do the syntax.
For example, I have a function (that works fine by itself)
Brenner=fmeasure(Image,’BREN’,[]); %Focus metric
And I have tried to call it into Blockproc via:
fh = @(bs) fmeasure(bs.data,’BREN’,[]);
It doesn’t work properly.Hello, I a trying to speed up some analysis of an image (4700 v 128 pixels) that needs breaking up into smaller regions (20×128 pixels) and for each region having a calculation done such as the standard deviation (std2)
I thought the combination of Blockproc and the parallel toolbox would be ideal for this.
However, when I run my analysis, I sometmes get a fast completion time of 0.25s, but other times I run it it can take upto 3s.
1: When I start up my matlab session, i start a parallel pool:
% For parallel Processing (init parpool here)
delete(gcp(‘nocreate’)); % but delete any that are already running
c=parcluster(‘local’);
numwks=c.NumWorkers;
ReportMessage(app,[‘Parallel processing: NumWorkers = ‘,num2str(numwks)]);
parpool(‘Processes’,numwks);
p=gcp;
conn=p.Connected;
ReportMessage(app,[‘…Connected ‘,num2str(conn)]);
2: I then run my fucntion from a push button callback.
My function first gets an image off a uiaxes, crops it and then performs the blockproc.
% Fast Analysis (SD)
tstart=tic;
ax=app.UIAxes;
IM=getimage(ax);
[sy,sx]=size(IM);
xl=5950; xr=10680; yb=0; yt=0; dx=xr-xl; % This is for image cropping
rect=[xl, yb, xr-xl,sy-yt-yb]; %[x, y, width, height]
IM2=imcrop(IM,rect);
IM=IM2-min(IM2(:)); % Background subtract
[sy,sx]=size(IM);
ColSize=20; % Number of pixels in each ROI – 20 default
nCols=floor(sx/ColSize);
RowSize = 128;
%BlockProc with Parallel
bss = [RowSize,ColSize]; % Each blockproc region
fh = @(bs) std2(bs.data); % perform this on each block
J = blockproc(IM, bss, fh,’UseParallel’,true);
sd=J’; % Column vector
ReportMessage(app,num2str(toc(tstart)));
Is there something I am doing wrong? Do I need to close and reopen the parpool everytime or something.
Also, if I want the fh function to be a functio that has more than 1 argument, how do I do the syntax.
For example, I have a function (that works fine by itself)
Brenner=fmeasure(Image,’BREN’,[]); %Focus metric
And I have tried to call it into Blockproc via:
fh = @(bs) fmeasure(bs.data,’BREN’,[]);
It doesn’t work properly. Hello, I a trying to speed up some analysis of an image (4700 v 128 pixels) that needs breaking up into smaller regions (20×128 pixels) and for each region having a calculation done such as the standard deviation (std2)
I thought the combination of Blockproc and the parallel toolbox would be ideal for this.
However, when I run my analysis, I sometmes get a fast completion time of 0.25s, but other times I run it it can take upto 3s.
1: When I start up my matlab session, i start a parallel pool:
% For parallel Processing (init parpool here)
delete(gcp(‘nocreate’)); % but delete any that are already running
c=parcluster(‘local’);
numwks=c.NumWorkers;
ReportMessage(app,[‘Parallel processing: NumWorkers = ‘,num2str(numwks)]);
parpool(‘Processes’,numwks);
p=gcp;
conn=p.Connected;
ReportMessage(app,[‘…Connected ‘,num2str(conn)]);
2: I then run my fucntion from a push button callback.
My function first gets an image off a uiaxes, crops it and then performs the blockproc.
% Fast Analysis (SD)
tstart=tic;
ax=app.UIAxes;
IM=getimage(ax);
[sy,sx]=size(IM);
xl=5950; xr=10680; yb=0; yt=0; dx=xr-xl; % This is for image cropping
rect=[xl, yb, xr-xl,sy-yt-yb]; %[x, y, width, height]
IM2=imcrop(IM,rect);
IM=IM2-min(IM2(:)); % Background subtract
[sy,sx]=size(IM);
ColSize=20; % Number of pixels in each ROI – 20 default
nCols=floor(sx/ColSize);
RowSize = 128;
%BlockProc with Parallel
bss = [RowSize,ColSize]; % Each blockproc region
fh = @(bs) std2(bs.data); % perform this on each block
J = blockproc(IM, bss, fh,’UseParallel’,true);
sd=J’; % Column vector
ReportMessage(app,num2str(toc(tstart)));
Is there something I am doing wrong? Do I need to close and reopen the parpool everytime or something.
Also, if I want the fh function to be a functio that has more than 1 argument, how do I do the syntax.
For example, I have a function (that works fine by itself)
Brenner=fmeasure(Image,’BREN’,[]); %Focus metric
And I have tried to call it into Blockproc via:
fh = @(bs) fmeasure(bs.data,’BREN’,[]);
It doesn’t work properly. parpool, blockproc, parallel computing toolbox MATLAB Answers — New Questions
How to change the arrangement of plots in a tiled layout even if the plots are not empty?
Is is still not possible to change e.g. from horizontal to vertical arrangment? Why is this not comming?!Is is still not possible to change e.g. from horizontal to vertical arrangment? Why is this not comming?! Is is still not possible to change e.g. from horizontal to vertical arrangment? Why is this not comming?! tiledlayout MATLAB Answers — New Questions
How do I reduce the amount of vectors I get from the gradient function without compromising resolution?
The gradient function returns the gradient of a scalar function (in the 3-dimensional case) depending on z-values, which means the gradient is approximated. To get a better approximation it would be best to feed as much z-values into the gradient function as possible. The function returns a gradient vector for every z-value fed to the function. Wanting to visualize the gradient, this means that for higher resolution gradients a lot of vectors are generated, which can create cluttered visualization (i.e. figure 1, where the blue lines underneath the curve represent the gradient vectors).
Is it possible to reduce the amount of vectors returned by the gradient function to improve visualization?The gradient function returns the gradient of a scalar function (in the 3-dimensional case) depending on z-values, which means the gradient is approximated. To get a better approximation it would be best to feed as much z-values into the gradient function as possible. The function returns a gradient vector for every z-value fed to the function. Wanting to visualize the gradient, this means that for higher resolution gradients a lot of vectors are generated, which can create cluttered visualization (i.e. figure 1, where the blue lines underneath the curve represent the gradient vectors).
Is it possible to reduce the amount of vectors returned by the gradient function to improve visualization? The gradient function returns the gradient of a scalar function (in the 3-dimensional case) depending on z-values, which means the gradient is approximated. To get a better approximation it would be best to feed as much z-values into the gradient function as possible. The function returns a gradient vector for every z-value fed to the function. Wanting to visualize the gradient, this means that for higher resolution gradients a lot of vectors are generated, which can create cluttered visualization (i.e. figure 1, where the blue lines underneath the curve represent the gradient vectors).
Is it possible to reduce the amount of vectors returned by the gradient function to improve visualization? gradient, vectors MATLAB Answers — New Questions
system command error within a parfor
Hi all,
I’m getting this error when runnning the code below. I isolated the issue to the use of the system command within the parfor loop. Note however that the same exact code runs fine on another -windows- PC.
Error Identifier: MATLAB:parallel:future:FetchNextFutureErrored
Error Message: The function evaluation completed with an error.
parfor ……
…..
command = …;
system(command);
endHi all,
I’m getting this error when runnning the code below. I isolated the issue to the use of the system command within the parfor loop. Note however that the same exact code runs fine on another -windows- PC.
Error Identifier: MATLAB:parallel:future:FetchNextFutureErrored
Error Message: The function evaluation completed with an error.
parfor ……
…..
command = …;
system(command);
end Hi all,
I’m getting this error when runnning the code below. I isolated the issue to the use of the system command within the parfor loop. Note however that the same exact code runs fine on another -windows- PC.
Error Identifier: MATLAB:parallel:future:FetchNextFutureErrored
Error Message: The function evaluation completed with an error.
parfor ……
…..
command = …;
system(command);
end parallel computing, parfor, system MATLAB Answers — New Questions
How to preserve the 3d plot box, when changing patch visibility.
I have a 3d plot with a collection of patches. If I set a subset of patches Visible attributes to ‘off’, the plot box is recomputed. How can I capture and preserve all aspects of the plot box so that the visible patches don’t jump around as other patches become visible or invisible.I have a 3d plot with a collection of patches. If I set a subset of patches Visible attributes to ‘off’, the plot box is recomputed. How can I capture and preserve all aspects of the plot box so that the visible patches don’t jump around as other patches become visible or invisible. I have a 3d plot with a collection of patches. If I set a subset of patches Visible attributes to ‘off’, the plot box is recomputed. How can I capture and preserve all aspects of the plot box so that the visible patches don’t jump around as other patches become visible or invisible. 3d plots, plot box, plot view MATLAB Answers — New Questions
MATLAB Coder generated MEX file throws an error that “Index exceeds matrix dimensions” although the code runs in MATLAB without error
I’m trying to use MATLAB Coder to generate C/C++ code for my MATLAB code. However, when I try to execute the MEX file generated by MATLAB Coder, it throws an error that for a specific variable that the index exceeds matrix dimensions:
>> myCode_mex
Index exceeds matrix dimensions. The array ‘A’ is empty and therefore has no valid indices.
The error stack points to the following MATLAB source code where I perform array extension:
n = length(A);
if n < buffSize
A(n+1) = data;
The same code however runs in MATLAB without any issues. Why does this happen?I’m trying to use MATLAB Coder to generate C/C++ code for my MATLAB code. However, when I try to execute the MEX file generated by MATLAB Coder, it throws an error that for a specific variable that the index exceeds matrix dimensions:
>> myCode_mex
Index exceeds matrix dimensions. The array ‘A’ is empty and therefore has no valid indices.
The error stack points to the following MATLAB source code where I perform array extension:
n = length(A);
if n < buffSize
A(n+1) = data;
The same code however runs in MATLAB without any issues. Why does this happen? I’m trying to use MATLAB Coder to generate C/C++ code for my MATLAB code. However, when I try to execute the MEX file generated by MATLAB Coder, it throws an error that for a specific variable that the index exceeds matrix dimensions:
>> myCode_mex
Index exceeds matrix dimensions. The array ‘A’ is empty and therefore has no valid indices.
The error stack points to the following MATLAB source code where I perform array extension:
n = length(A);
if n < buffSize
A(n+1) = data;
The same code however runs in MATLAB without any issues. Why does this happen? array, index, exceeds, matrix, matlab, coder, extension, ml, codegen MATLAB Answers — New Questions
Confidence interval in fit
By default, the fit function in matlab returns 95 % confidence interval bounds. I want it to return error as defined by 1 sigma confidence, which i think corresponds to 68.27% confidence bound. How do i get this?By default, the fit function in matlab returns 95 % confidence interval bounds. I want it to return error as defined by 1 sigma confidence, which i think corresponds to 68.27% confidence bound. How do i get this? By default, the fit function in matlab returns 95 % confidence interval bounds. I want it to return error as defined by 1 sigma confidence, which i think corresponds to 68.27% confidence bound. How do i get this? curve fitting, nonlinear, error MATLAB Answers — New Questions
Method lookup in multiple inheritance
I defined four classes: a, b, c, and d. Class a defines a method f; class b inherits from a and overrides f; class c inherits from a; class d inherits from both b and c.
Why does calling f(d) print ‘b’? What is MATLAB’s method lookup mechanism?
classdef a
methods
function f(obj)
‘a’
end
end
end
classdef b < a
methods
function f(obj)
‘b’
end
end
end
classdef c < a
methods
end
end
classdef d < a
methods
end
endI defined four classes: a, b, c, and d. Class a defines a method f; class b inherits from a and overrides f; class c inherits from a; class d inherits from both b and c.
Why does calling f(d) print ‘b’? What is MATLAB’s method lookup mechanism?
classdef a
methods
function f(obj)
‘a’
end
end
end
classdef b < a
methods
function f(obj)
‘b’
end
end
end
classdef c < a
methods
end
end
classdef d < a
methods
end
end I defined four classes: a, b, c, and d. Class a defines a method f; class b inherits from a and overrides f; class c inherits from a; class d inherits from both b and c.
Why does calling f(d) print ‘b’? What is MATLAB’s method lookup mechanism?
classdef a
methods
function f(obj)
‘a’
end
end
end
classdef b < a
methods
function f(obj)
‘b’
end
end
end
classdef c < a
methods
end
end
classdef d < a
methods
end
end multiple inheritance MATLAB Answers — New Questions
what’s wrong with matlab dsolve ?
I am using this matlab version
‘24.2.0.2806996 (R2024b) Update
Example:
——————————————-
syms u(t) a
sl = dsolve( diff(u,t) == sqrt( u^2+a^2) )
sl =
-a*1i
a*1i
exp(C1 + t)/2 – (a^2*exp(- C1 – t))/2
——————————————
Apart from the constant solution,
the correct solution is
u(t) = a*sinh( t+ const.)
which is different than the matlab solution unless a^2 = 1
What’s wrong with dsolve ?I am using this matlab version
‘24.2.0.2806996 (R2024b) Update
Example:
——————————————-
syms u(t) a
sl = dsolve( diff(u,t) == sqrt( u^2+a^2) )
sl =
-a*1i
a*1i
exp(C1 + t)/2 – (a^2*exp(- C1 – t))/2
——————————————
Apart from the constant solution,
the correct solution is
u(t) = a*sinh( t+ const.)
which is different than the matlab solution unless a^2 = 1
What’s wrong with dsolve ? I am using this matlab version
‘24.2.0.2806996 (R2024b) Update
Example:
——————————————-
syms u(t) a
sl = dsolve( diff(u,t) == sqrt( u^2+a^2) )
sl =
-a*1i
a*1i
exp(C1 + t)/2 – (a^2*exp(- C1 – t))/2
——————————————
Apart from the constant solution,
the correct solution is
u(t) = a*sinh( t+ const.)
which is different than the matlab solution unless a^2 = 1
What’s wrong with dsolve ? dsolve MATLAB Answers — New Questions
Some figures not saving as vector graphics (.svg)
Hi,
I ran into a strange problem. I’m trying to save figures in vector format to process in Adobe Illustrator. I make numerous of these plots using one script and in many cases the output to vector graphics using the .svg format works fine. Some figures, made by the same script and apart from the specific datapoints indistinguishable from other figures, do not export as proper vector graphics. In those cases I can open the output .svg file in Illustrator but the image is basically flat; i.e. I can not isolate individual elements for editing.
I have attached two figures extracted at the exact point in the script where the data is added that causes it to not save properly. I plot datapoints on a trial-trial basis, adding data from one trial, then the data from the next trial etc. Until a particular trial I can save the figure as a proper vector graphic .svg file (attached as Fig1Vector.fig). When data from the next trial is added, the output .svg file only contains a flattened image (attached as Fig2NotVector.fig).
I’ve been looking for differences between the two figures but I have exhausted my ideas on what could be at cause. Do any of you have any idea what could be going wrong here or any suggestions to do a successful vector image export?
Thanks in advance.
Best,
PaulHi,
I ran into a strange problem. I’m trying to save figures in vector format to process in Adobe Illustrator. I make numerous of these plots using one script and in many cases the output to vector graphics using the .svg format works fine. Some figures, made by the same script and apart from the specific datapoints indistinguishable from other figures, do not export as proper vector graphics. In those cases I can open the output .svg file in Illustrator but the image is basically flat; i.e. I can not isolate individual elements for editing.
I have attached two figures extracted at the exact point in the script where the data is added that causes it to not save properly. I plot datapoints on a trial-trial basis, adding data from one trial, then the data from the next trial etc. Until a particular trial I can save the figure as a proper vector graphic .svg file (attached as Fig1Vector.fig). When data from the next trial is added, the output .svg file only contains a flattened image (attached as Fig2NotVector.fig).
I’ve been looking for differences between the two figures but I have exhausted my ideas on what could be at cause. Do any of you have any idea what could be going wrong here or any suggestions to do a successful vector image export?
Thanks in advance.
Best,
Paul Hi,
I ran into a strange problem. I’m trying to save figures in vector format to process in Adobe Illustrator. I make numerous of these plots using one script and in many cases the output to vector graphics using the .svg format works fine. Some figures, made by the same script and apart from the specific datapoints indistinguishable from other figures, do not export as proper vector graphics. In those cases I can open the output .svg file in Illustrator but the image is basically flat; i.e. I can not isolate individual elements for editing.
I have attached two figures extracted at the exact point in the script where the data is added that causes it to not save properly. I plot datapoints on a trial-trial basis, adding data from one trial, then the data from the next trial etc. Until a particular trial I can save the figure as a proper vector graphic .svg file (attached as Fig1Vector.fig). When data from the next trial is added, the output .svg file only contains a flattened image (attached as Fig2NotVector.fig).
I’ve been looking for differences between the two figures but I have exhausted my ideas on what could be at cause. Do any of you have any idea what could be going wrong here or any suggestions to do a successful vector image export?
Thanks in advance.
Best,
Paul figure, export, saveas, plot, save, vector graphics, svg, fig MATLAB Answers — New Questions
Section folding not present
Using R2024B, i got the option to use the live editor and some things changed without asking.
Most importantly, the + buttons to fold a section have dissappeared, while in preferences/editor/code folding the option sections is ON.
Another change is that the titles of the scripts are in an additional column.
FInally, beneath the folder section, there is a new window with the ‘script’ , i.e. a shortcut to jump to a section.
How can I get the section folding again?
Cheers, PaulUsing R2024B, i got the option to use the live editor and some things changed without asking.
Most importantly, the + buttons to fold a section have dissappeared, while in preferences/editor/code folding the option sections is ON.
Another change is that the titles of the scripts are in an additional column.
FInally, beneath the folder section, there is a new window with the ‘script’ , i.e. a shortcut to jump to a section.
How can I get the section folding again?
Cheers, Paul Using R2024B, i got the option to use the live editor and some things changed without asking.
Most importantly, the + buttons to fold a section have dissappeared, while in preferences/editor/code folding the option sections is ON.
Another change is that the titles of the scripts are in an additional column.
FInally, beneath the folder section, there is a new window with the ‘script’ , i.e. a shortcut to jump to a section.
How can I get the section folding again?
Cheers, Paul section folding MATLAB Answers — New Questions
Why is there not a button for FIK and License file?
It’s impossible to find these 2 pieces of info. Please create a button pointing to them next to the license number.It’s impossible to find these 2 pieces of info. Please create a button pointing to them next to the license number. It’s impossible to find these 2 pieces of info. Please create a button pointing to them next to the license number. fik MATLAB Answers — New Questions
Modeling load-depend friction in bearings in Simscape
Hi everyone,
i’m trying to model a five-point double-toggle lever with bearings with load-dependent friction, based on the normal-force (Coulomb, which is constant at any velocity).
I’ve tried modeling the bearing with the Multibody Interface and Rotational Friction, but i can only add a constant friction torque. When i calculate the torque using the measured normal force of the bearing, I get an algebraic loop. Is it possible to apply a load dependent Torque (Tr = Fr*d/2 = Fn*µ*d/2) and a friction force (Fr = µ*Fn) without creating algebraic loops?
Note on the image below: The force Rij is calculated as R = µ*N and acts opposite to the velocity. If R is transformed to the center, this results in atorque (T = r*R), acting opposite to the velocity.
Best greetings!Hi everyone,
i’m trying to model a five-point double-toggle lever with bearings with load-dependent friction, based on the normal-force (Coulomb, which is constant at any velocity).
I’ve tried modeling the bearing with the Multibody Interface and Rotational Friction, but i can only add a constant friction torque. When i calculate the torque using the measured normal force of the bearing, I get an algebraic loop. Is it possible to apply a load dependent Torque (Tr = Fr*d/2 = Fn*µ*d/2) and a friction force (Fr = µ*Fn) without creating algebraic loops?
Note on the image below: The force Rij is calculated as R = µ*N and acts opposite to the velocity. If R is transformed to the center, this results in atorque (T = r*R), acting opposite to the velocity.
Best greetings! Hi everyone,
i’m trying to model a five-point double-toggle lever with bearings with load-dependent friction, based on the normal-force (Coulomb, which is constant at any velocity).
I’ve tried modeling the bearing with the Multibody Interface and Rotational Friction, but i can only add a constant friction torque. When i calculate the torque using the measured normal force of the bearing, I get an algebraic loop. Is it possible to apply a load dependent Torque (Tr = Fr*d/2 = Fn*µ*d/2) and a friction force (Fr = µ*Fn) without creating algebraic loops?
Note on the image below: The force Rij is calculated as R = µ*N and acts opposite to the velocity. If R is transformed to the center, this results in atorque (T = r*R), acting opposite to the velocity.
Best greetings! simulink, friction, bearing, simscape, loop MATLAB Answers — New Questions
Custom storage class for Argument Simulink parameters identifiable by TLC script
Hi,
My objective is to define a custom storage class specifically intended for "Argument" Simulink parameters. The primary requirement is to programmatically identify which model parameters are using this custom storage class from within a TLC script executed during code generation.
I initially attempted to create the custom storage class using an Embedded Coder Dictionary. However, at code generation time, I have been unable to definitively determine which model parameters are using my custom storage class. The only observable indicator appears to be the field ModelParameters.Parameter[i].IsSpecifiedAsNewStorageClass, which is set to 1. I would appreciate confirmation on whether this is the intended mechanism or if additional fields should be accessible.
I subsequently explored the Custom Storage Class Designer, which showed promise. Upon inspection, the custom storage class appeared clearly within the TLC script context under the CustomStorageClasses record. However, as far as I know, it is not possible to define a custom storage class for "Argument" Simulink parameters this way.
Are there any aspects of either methodology that I may have overlooked or configured incorrectly?
Is there an alternative approach or recommended candidate method that would better satisfy my requirements?
Best regardsHi,
My objective is to define a custom storage class specifically intended for "Argument" Simulink parameters. The primary requirement is to programmatically identify which model parameters are using this custom storage class from within a TLC script executed during code generation.
I initially attempted to create the custom storage class using an Embedded Coder Dictionary. However, at code generation time, I have been unable to definitively determine which model parameters are using my custom storage class. The only observable indicator appears to be the field ModelParameters.Parameter[i].IsSpecifiedAsNewStorageClass, which is set to 1. I would appreciate confirmation on whether this is the intended mechanism or if additional fields should be accessible.
I subsequently explored the Custom Storage Class Designer, which showed promise. Upon inspection, the custom storage class appeared clearly within the TLC script context under the CustomStorageClasses record. However, as far as I know, it is not possible to define a custom storage class for "Argument" Simulink parameters this way.
Are there any aspects of either methodology that I may have overlooked or configured incorrectly?
Is there an alternative approach or recommended candidate method that would better satisfy my requirements?
Best regards Hi,
My objective is to define a custom storage class specifically intended for "Argument" Simulink parameters. The primary requirement is to programmatically identify which model parameters are using this custom storage class from within a TLC script executed during code generation.
I initially attempted to create the custom storage class using an Embedded Coder Dictionary. However, at code generation time, I have been unable to definitively determine which model parameters are using my custom storage class. The only observable indicator appears to be the field ModelParameters.Parameter[i].IsSpecifiedAsNewStorageClass, which is set to 1. I would appreciate confirmation on whether this is the intended mechanism or if additional fields should be accessible.
I subsequently explored the Custom Storage Class Designer, which showed promise. Upon inspection, the custom storage class appeared clearly within the TLC script context under the CustomStorageClasses record. However, as far as I know, it is not possible to define a custom storage class for "Argument" Simulink parameters this way.
Are there any aspects of either methodology that I may have overlooked or configured incorrectly?
Is there an alternative approach or recommended candidate method that would better satisfy my requirements?
Best regards code generation, simulink parameters, storage class MATLAB Answers — New Questions
DLL fails to load – matlabruntimeforpython_abi3
Hi all,
I’ve been struggling with this one for a few days now. I’m looking for proof of concept program that I can package a matlab function and then import it to my python executable. So far everything runs great in a terminal, but after using PyInstaller to generate the executable the I cannot get it to run. I’ve installed the MATLAB 2025b runtime and did install the package that was generated using the Python Package Compiler in MATLAB.
I get the following output in my command window when I attempt to launch matlab_test.exe:
My MATLAB function:
function a = matlab2python(b)
a = sqrt(b);
end
My python code:
import os
import sys
import time
import matlabsdk as sdk_python_test
import matlab
if __name__ == "__main__":
pkg = sdk_python_test.initialize()
result = pkg.matlab2python(9.0)
print(result)
pkg.terminate()Hi all,
I’ve been struggling with this one for a few days now. I’m looking for proof of concept program that I can package a matlab function and then import it to my python executable. So far everything runs great in a terminal, but after using PyInstaller to generate the executable the I cannot get it to run. I’ve installed the MATLAB 2025b runtime and did install the package that was generated using the Python Package Compiler in MATLAB.
I get the following output in my command window when I attempt to launch matlab_test.exe:
My MATLAB function:
function a = matlab2python(b)
a = sqrt(b);
end
My python code:
import os
import sys
import time
import matlabsdk as sdk_python_test
import matlab
if __name__ == "__main__":
pkg = sdk_python_test.initialize()
result = pkg.matlab2python(9.0)
print(result)
pkg.terminate() Hi all,
I’ve been struggling with this one for a few days now. I’m looking for proof of concept program that I can package a matlab function and then import it to my python executable. So far everything runs great in a terminal, but after using PyInstaller to generate the executable the I cannot get it to run. I’ve installed the MATLAB 2025b runtime and did install the package that was generated using the Python Package Compiler in MATLAB.
I get the following output in my command window when I attempt to launch matlab_test.exe:
My MATLAB function:
function a = matlab2python(b)
a = sqrt(b);
end
My python code:
import os
import sys
import time
import matlabsdk as sdk_python_test
import matlab
if __name__ == "__main__":
pkg = sdk_python_test.initialize()
result = pkg.matlab2python(9.0)
print(result)
pkg.terminate() pyinstaller, python312 MATLAB Answers — New Questions
How to place code generated from subsystem into RAM on Ti C2000?
I am trying to plase parts of the code generated from one of the subsystems into RAM to speed up execution. The help provided in Control Data and Function Placement in Memory by Inserting Pragmas is not sufficient.
Is there a better explanation on how to add #pragma CODE_SECTION(myCriticalTask, "ramfuncs") to the generated function?
Do I need to edit linker command file?
Do I need to add code to copy function from flash to RAM on power up?
Thanks.I am trying to plase parts of the code generated from one of the subsystems into RAM to speed up execution. The help provided in Control Data and Function Placement in Memory by Inserting Pragmas is not sufficient.
Is there a better explanation on how to add #pragma CODE_SECTION(myCriticalTask, "ramfuncs") to the generated function?
Do I need to edit linker command file?
Do I need to add code to copy function from flash to RAM on power up?
Thanks. I am trying to plase parts of the code generated from one of the subsystems into RAM to speed up execution. The help provided in Control Data and Function Placement in Memory by Inserting Pragmas is not sufficient.
Is there a better explanation on how to add #pragma CODE_SECTION(myCriticalTask, "ramfuncs") to the generated function?
Do I need to edit linker command file?
Do I need to add code to copy function from flash to RAM on power up?
Thanks. c2000, matlab, simulink, embedded coder MATLAB Answers — New Questions
Clarification on Sampling Rate vs. Control Bandwidth in Average Current Mode Control for Buck Converter
I am implementing Average Current Mode Control for a Buck converter. According to control theory, the voltage loop (outer loop) is typically designed to be 5–10 times slower than the current loop (inner loop) to ensure stability and proper decoupling.
However, in my current simulation setup, the ADC for both voltage and current is triggered at the same time. Does this imply that the execution frequency (sampling rate) of both control loops must be identical?
How can I implement a slower voltage loop while maintaining the same ADC sampling frequency for both signals in Simulink/Embedded C? Any insights on whether this ‘simultaneous sampling’ contradicts the principle of having a slower outer loop would be greatly appreciatedI am implementing Average Current Mode Control for a Buck converter. According to control theory, the voltage loop (outer loop) is typically designed to be 5–10 times slower than the current loop (inner loop) to ensure stability and proper decoupling.
However, in my current simulation setup, the ADC for both voltage and current is triggered at the same time. Does this imply that the execution frequency (sampling rate) of both control loops must be identical?
How can I implement a slower voltage loop while maintaining the same ADC sampling frequency for both signals in Simulink/Embedded C? Any insights on whether this ‘simultaneous sampling’ contradicts the principle of having a slower outer loop would be greatly appreciated I am implementing Average Current Mode Control for a Buck converter. According to control theory, the voltage loop (outer loop) is typically designed to be 5–10 times slower than the current loop (inner loop) to ensure stability and proper decoupling.
However, in my current simulation setup, the ADC for both voltage and current is triggered at the same time. Does this imply that the execution frequency (sampling rate) of both control loops must be identical?
How can I implement a slower voltage loop while maintaining the same ADC sampling frequency for both signals in Simulink/Embedded C? Any insights on whether this ‘simultaneous sampling’ contradicts the principle of having a slower outer loop would be greatly appreciated average current mode, cascaded control MATLAB Answers — New Questions
Flexibility in Satellite Toolbox
Is there any way to both add and visualize customized gimbals and/or sensors to the satellite toolbox?
My particular scenario is looking at putting a camera on a platform but limiting the gimbal angles and field-of-view non-symmetrically.
The FOV is different in along and cross track directions (not conical). While other toolboxes have "rectangular" FOVs, I don’t see the capability in the satellite toolbox. Functions could be added to filter, but they won’t visualize properly.
My gimbals are pitch and roll rather than azimuth and elevation. I can compute the corresponding angles, but wondering if there’s a way to change how gimbals are controlled.
My gimbals don’t have complete freedom to move throughout the entire hemisphere. Again, results can be filtered but the visualization doesn’t correspond.
Is there currently (or possibly in the future) a path to customizing gimbals or sensors (with visualization) in this toolbox? Maybe an API?Is there any way to both add and visualize customized gimbals and/or sensors to the satellite toolbox?
My particular scenario is looking at putting a camera on a platform but limiting the gimbal angles and field-of-view non-symmetrically.
The FOV is different in along and cross track directions (not conical). While other toolboxes have "rectangular" FOVs, I don’t see the capability in the satellite toolbox. Functions could be added to filter, but they won’t visualize properly.
My gimbals are pitch and roll rather than azimuth and elevation. I can compute the corresponding angles, but wondering if there’s a way to change how gimbals are controlled.
My gimbals don’t have complete freedom to move throughout the entire hemisphere. Again, results can be filtered but the visualization doesn’t correspond.
Is there currently (or possibly in the future) a path to customizing gimbals or sensors (with visualization) in this toolbox? Maybe an API? Is there any way to both add and visualize customized gimbals and/or sensors to the satellite toolbox?
My particular scenario is looking at putting a camera on a platform but limiting the gimbal angles and field-of-view non-symmetrically.
The FOV is different in along and cross track directions (not conical). While other toolboxes have "rectangular" FOVs, I don’t see the capability in the satellite toolbox. Functions could be added to filter, but they won’t visualize properly.
My gimbals are pitch and roll rather than azimuth and elevation. I can compute the corresponding angles, but wondering if there’s a way to change how gimbals are controlled.
My gimbals don’t have complete freedom to move throughout the entire hemisphere. Again, results can be filtered but the visualization doesn’t correspond.
Is there currently (or possibly in the future) a path to customizing gimbals or sensors (with visualization) in this toolbox? Maybe an API? satellitetoolbox, gimbal, concialsensor MATLAB Answers — New Questions
Simulink simulation becomes very slow after adding FOC to a 6-phase PMSM drive with CHB inverter
I am simulating an asymmetrical six-phase PMSM drive in Simulink (R2025b).
The original model consisted of:
– 5-level cascaded H-bridge inverter
– phase-shifted PWM (PSPWM)
– asymmetrical 6-phase PMSM (30° phase shift)
In this configuration the simulation runs normally. After introducing field-oriented control (FOC) the simulation becomes very slow.
The FOC implementation includes:
– VSD transformation (abc-def → αβxy)
– Park transformation
– PI current controllers (id, iq, ix, iy)
– speed PI controller
– inverse transformations
– discrete current filters ( for i_αβ)
Main parameters:
– PWM carrier frequency: fcr = 5 kHz
– duty cycle update rate: 100 kHz
– solver: ode14x
– Simulink version: R2025b
The electrical model of the inverter and machine has not changed, only the control structure was added.
My question is: Is it normal that adding FOC significantly slows down the simulation in Simulink, and what are recommended practices to keep such motor drive simulations efficient (solver choice, controller sampling rates, or implementation of transformations)?I am simulating an asymmetrical six-phase PMSM drive in Simulink (R2025b).
The original model consisted of:
– 5-level cascaded H-bridge inverter
– phase-shifted PWM (PSPWM)
– asymmetrical 6-phase PMSM (30° phase shift)
In this configuration the simulation runs normally. After introducing field-oriented control (FOC) the simulation becomes very slow.
The FOC implementation includes:
– VSD transformation (abc-def → αβxy)
– Park transformation
– PI current controllers (id, iq, ix, iy)
– speed PI controller
– inverse transformations
– discrete current filters ( for i_αβ)
Main parameters:
– PWM carrier frequency: fcr = 5 kHz
– duty cycle update rate: 100 kHz
– solver: ode14x
– Simulink version: R2025b
The electrical model of the inverter and machine has not changed, only the control structure was added.
My question is: Is it normal that adding FOC significantly slows down the simulation in Simulink, and what are recommended practices to keep such motor drive simulations efficient (solver choice, controller sampling rates, or implementation of transformations)? I am simulating an asymmetrical six-phase PMSM drive in Simulink (R2025b).
The original model consisted of:
– 5-level cascaded H-bridge inverter
– phase-shifted PWM (PSPWM)
– asymmetrical 6-phase PMSM (30° phase shift)
In this configuration the simulation runs normally. After introducing field-oriented control (FOC) the simulation becomes very slow.
The FOC implementation includes:
– VSD transformation (abc-def → αβxy)
– Park transformation
– PI current controllers (id, iq, ix, iy)
– speed PI controller
– inverse transformations
– discrete current filters ( for i_αβ)
Main parameters:
– PWM carrier frequency: fcr = 5 kHz
– duty cycle update rate: 100 kHz
– solver: ode14x
– Simulink version: R2025b
The electrical model of the inverter and machine has not changed, only the control structure was added.
My question is: Is it normal that adding FOC significantly slows down the simulation in Simulink, and what are recommended practices to keep such motor drive simulations efficient (solver choice, controller sampling rates, or implementation of transformations)? simulink, motor-control, pmsm, foc, power_electronics_control MATLAB Answers — New Questions









