Tag Archives: matlab
How to write a subclass that `copies’ an instance of the superclass?
Basic Question: Can I make a copy of an instance of a class, but with a different version of one of the class’s methods?
Details: I have a class called Domain2d which has a method threePointQuadrature. I want to rewrite the threePointQuadrature method and run tests to compare the new method versus the old method. The idea I have is to make Domain2d_exp < Domain2d which is the same in every way as Domain2d, except I will write an experimental version of the threePointQuadrature method in Domain2d_exp.
My understanding is that subclasses inherit all methods from the superclass, but will run the subclass version of a method if the subclass has a method with the same name as one of the superclass methods. So, if I have dom (an instance of Domain2d) and dom_exp (an instance of Domain2d_exp) then when I call dom.threePointQuadrature, the original version of the function will be run, and when I call dom_exp.threePointQuadrature, the the experimental version of threePointQuadrature will be run.
Now, since Domain2d_exp < Domain2d I would normally write the constructor for Domain2d_exp to take the same parameters as Domain2d, and then just call the superclass constructor for Domain2d from within the constructor for Domain2d_exp. However, the issue in this case is that once a Domain2d object has been instantiated, it must be configured, which requires several other lines of code, and is somewhat costly in terms of time. So what I’d rather do is instantiate and configure dom, and instance of Domain2d, and then pass dom to the constructor for Domain2d_exp, which will retain all the properties and methods of dom, but with the experimental threePointQuadrature method.
Is this possible? Or, is there a better way to acheive the same end result?Basic Question: Can I make a copy of an instance of a class, but with a different version of one of the class’s methods?
Details: I have a class called Domain2d which has a method threePointQuadrature. I want to rewrite the threePointQuadrature method and run tests to compare the new method versus the old method. The idea I have is to make Domain2d_exp < Domain2d which is the same in every way as Domain2d, except I will write an experimental version of the threePointQuadrature method in Domain2d_exp.
My understanding is that subclasses inherit all methods from the superclass, but will run the subclass version of a method if the subclass has a method with the same name as one of the superclass methods. So, if I have dom (an instance of Domain2d) and dom_exp (an instance of Domain2d_exp) then when I call dom.threePointQuadrature, the original version of the function will be run, and when I call dom_exp.threePointQuadrature, the the experimental version of threePointQuadrature will be run.
Now, since Domain2d_exp < Domain2d I would normally write the constructor for Domain2d_exp to take the same parameters as Domain2d, and then just call the superclass constructor for Domain2d from within the constructor for Domain2d_exp. However, the issue in this case is that once a Domain2d object has been instantiated, it must be configured, which requires several other lines of code, and is somewhat costly in terms of time. So what I’d rather do is instantiate and configure dom, and instance of Domain2d, and then pass dom to the constructor for Domain2d_exp, which will retain all the properties and methods of dom, but with the experimental threePointQuadrature method.
Is this possible? Or, is there a better way to acheive the same end result? Basic Question: Can I make a copy of an instance of a class, but with a different version of one of the class’s methods?
Details: I have a class called Domain2d which has a method threePointQuadrature. I want to rewrite the threePointQuadrature method and run tests to compare the new method versus the old method. The idea I have is to make Domain2d_exp < Domain2d which is the same in every way as Domain2d, except I will write an experimental version of the threePointQuadrature method in Domain2d_exp.
My understanding is that subclasses inherit all methods from the superclass, but will run the subclass version of a method if the subclass has a method with the same name as one of the superclass methods. So, if I have dom (an instance of Domain2d) and dom_exp (an instance of Domain2d_exp) then when I call dom.threePointQuadrature, the original version of the function will be run, and when I call dom_exp.threePointQuadrature, the the experimental version of threePointQuadrature will be run.
Now, since Domain2d_exp < Domain2d I would normally write the constructor for Domain2d_exp to take the same parameters as Domain2d, and then just call the superclass constructor for Domain2d from within the constructor for Domain2d_exp. However, the issue in this case is that once a Domain2d object has been instantiated, it must be configured, which requires several other lines of code, and is somewhat costly in terms of time. So what I’d rather do is instantiate and configure dom, and instance of Domain2d, and then pass dom to the constructor for Domain2d_exp, which will retain all the properties and methods of dom, but with the experimental threePointQuadrature method.
Is this possible? Or, is there a better way to acheive the same end result? classes, constructors MATLAB Answers — New Questions
Sending Data sensor from MATLAB Simulink to firebase
Hi,
I have a MATLAB Simulink model of an EV station electric with sensors such as a current sensor. I want to send the real-time sensor data to Firebase. Is there a methode to do connect MATLAB with Firebase databse?
Thanks,Hi,
I have a MATLAB Simulink model of an EV station electric with sensors such as a current sensor. I want to send the real-time sensor data to Firebase. Is there a methode to do connect MATLAB with Firebase databse?
Thanks, Hi,
I have a MATLAB Simulink model of an EV station electric with sensors such as a current sensor. I want to send the real-time sensor data to Firebase. Is there a methode to do connect MATLAB with Firebase databse?
Thanks, matlab, firebase MATLAB Answers — New Questions
what function for computing all subsets given an array of consecutive number?
Hi I’m a little lost looking up the function call for the task: computing all subset of this array, which has 12 consecutive numbers
So, like given we have
a = [1:12];
% need to get all 2^12 subsets [1, 2], [1, 2, 3]….
I’m trying but I don’t think combntns() could workHi I’m a little lost looking up the function call for the task: computing all subset of this array, which has 12 consecutive numbers
So, like given we have
a = [1:12];
% need to get all 2^12 subsets [1, 2], [1, 2, 3]….
I’m trying but I don’t think combntns() could work Hi I’m a little lost looking up the function call for the task: computing all subset of this array, which has 12 consecutive numbers
So, like given we have
a = [1:12];
% need to get all 2^12 subsets [1, 2], [1, 2, 3]….
I’m trying but I don’t think combntns() could work subsets MATLAB Answers — New Questions
Lorenz Attractor Animation with Frame-by-Frame Plotting
I was trying to create an animation of Lorenz Attractor. I used the following code but it did not give me the result I want like https://en.wikipedia.org/wiki/Lorenz_system.
% Parameters
sigma = 10;
rho = 28;
beta = 8/3;
% Time span
tspan = [0 50]; % Adjusted for smooth animation
% Initial conditions
y0 = [1; 1; 1];
% Lorenz system of equations
lorenz = @(t, y) [sigma * (y(2) – y(1));
y(1) * (rho – y(3)) – y(2);
y(1) * y(2) – beta * y(3)];
% Solve the system using ode45
[t, y] = ode45(lorenz, tspan, y0);
% Set up the figure for animation
figure;
h = plot3(y(1,1), y(1,2), y(1,3));
xlabel(‘X’);
ylabel(‘Y’);
zlabel(‘Z’);
title(‘Lorenz Attractor Animation’);
grid on;
axis([-20 20 -30 30 0 50]);
view(3);
hold on;
% Animate the Lorenz attractor
for i = 2:length(t)
% Update the plot data
h.XData = y(1:i, 1);
h.YData = y(1:i, 2);
h.ZData = y(1:i, 3);
% Refresh the figure
drawnow;
% Optional: Pause to slow down the animation if too fast
pause(0.01); % Adjust the pause time as needed
endI was trying to create an animation of Lorenz Attractor. I used the following code but it did not give me the result I want like https://en.wikipedia.org/wiki/Lorenz_system.
% Parameters
sigma = 10;
rho = 28;
beta = 8/3;
% Time span
tspan = [0 50]; % Adjusted for smooth animation
% Initial conditions
y0 = [1; 1; 1];
% Lorenz system of equations
lorenz = @(t, y) [sigma * (y(2) – y(1));
y(1) * (rho – y(3)) – y(2);
y(1) * y(2) – beta * y(3)];
% Solve the system using ode45
[t, y] = ode45(lorenz, tspan, y0);
% Set up the figure for animation
figure;
h = plot3(y(1,1), y(1,2), y(1,3));
xlabel(‘X’);
ylabel(‘Y’);
zlabel(‘Z’);
title(‘Lorenz Attractor Animation’);
grid on;
axis([-20 20 -30 30 0 50]);
view(3);
hold on;
% Animate the Lorenz attractor
for i = 2:length(t)
% Update the plot data
h.XData = y(1:i, 1);
h.YData = y(1:i, 2);
h.ZData = y(1:i, 3);
% Refresh the figure
drawnow;
% Optional: Pause to slow down the animation if too fast
pause(0.01); % Adjust the pause time as needed
end I was trying to create an animation of Lorenz Attractor. I used the following code but it did not give me the result I want like https://en.wikipedia.org/wiki/Lorenz_system.
% Parameters
sigma = 10;
rho = 28;
beta = 8/3;
% Time span
tspan = [0 50]; % Adjusted for smooth animation
% Initial conditions
y0 = [1; 1; 1];
% Lorenz system of equations
lorenz = @(t, y) [sigma * (y(2) – y(1));
y(1) * (rho – y(3)) – y(2);
y(1) * y(2) – beta * y(3)];
% Solve the system using ode45
[t, y] = ode45(lorenz, tspan, y0);
% Set up the figure for animation
figure;
h = plot3(y(1,1), y(1,2), y(1,3));
xlabel(‘X’);
ylabel(‘Y’);
zlabel(‘Z’);
title(‘Lorenz Attractor Animation’);
grid on;
axis([-20 20 -30 30 0 50]);
view(3);
hold on;
% Animate the Lorenz attractor
for i = 2:length(t)
% Update the plot data
h.XData = y(1:i, 1);
h.YData = y(1:i, 2);
h.ZData = y(1:i, 3);
% Refresh the figure
drawnow;
% Optional: Pause to slow down the animation if too fast
pause(0.01); % Adjust the pause time as needed
end ode45, differential equations, 3d plots MATLAB Answers — New Questions
Using Matlab Runge Kutta Routine
I’m having trouble with the following code. I’m trying to test it to get it to produce the final value as it proceeds through the count and increments the count, but it isn’t working. It won’t go past the first increment. I’m new to Matlab (once again). Can anyone assist me?
handle=[];
%Initial Conditions
pn0 = 0.0; %Initial north position
pe0 = 0.0; %initial east position
pd0 = -100.0; %initial east position
u0 =25.0; %initial velocity along body x-axis
v0 = 0.0; %initial velocity along body y-axis
w0 = 0.0; %initial velocity along body z-axis
phi0 = 0.0; %initial roll angle
theta0 = 0.0; %initial pitch angle
psi0 = 0.0; %initial yaw rate
l0 = 0; %initial moment about ib axis
m0 = 0; %initial moment about jb axis
n0 = 0; %initial moment about kb axis
p0 = 0; %initial roll rate along ib in Fb
q0 = 0; %initial pitch rate along jb in Fb
r0 = 0; %initial yaw rate along kb in Fb
Va0 = (u0^2 + v0^2 + w0^2)^0.5; %initial velocity
%Initial forces producing acceleration – fx, fy, fz
fx = 0; %Force in the ib direction.
fy = 0; %Force in the jb direciton.
fz = 0; %Force in the kb direction.
%Plane is initially aligned so that ib,jb, and kb
%correspond to x, y, z.
%Physical Parameters
mass = 11; % kg
Jx = 0.8244; %kg m^2
Jy = 1.135;
Jz = 1.759;
Jxz = 0.1204;
S_wing = 0.55;
b = 2.8956;
c = 0.18994;
Sprop = 0.2027;
rho = 1.2682;
e = 0.9;
AR = (b^2)/S_wing;
gravity = 9.81;
%Gamma Values
G = Jx * Jz – (Jxz^2);
G1 = (Jxz * (Jx – Jy + Jz))/ G ;
G2 = (Jz * (Jz – Jy) + (Jxz^2))/ G;
G3 = Jz / G;
G4 = Jxz / G;
G5 = (Jz – Jx) / Jy;
G6 = Jxz / Jy;
G7 = ((Jx – Jy) * Jx + (Jxz ^ 2)) / G;
G8 = Jx / G;
%Establish the parameters to pass to the subroutines
p = p0;
q = q0;
r = r0;
l = l0;
m = m0;
n = n0;
u = u0;
v = v0;
w = w0;
phi = phi0;
theta = theta0;
psi = psi0;
dt = 0.1;
fxone = fx;
fyone = fy;
fzone = fz;
fxtwo = 0;
fytwo = 0;
fztwo = 0;
n=0;
numsteps=100;
total_time = 100; % total simulation time in seconds
time_step = 0.1; % time step in seconds
num_steps = total_time / time_step; % number of steps
for count = 1:numsteps
clc;
clear all;
%Runge Kutta 4 attempt;
%fx = 5*t/mass
r=0
v=0;
q=0;
w=0;
mass = 10;
tstart = (count-1)*time_step;
tstop = tstart + 0.01;
tspan = [tstart,0.01,tstop];
y0=0.0;
[t,y]=ode45(@(t,y) (r*v-q*w)+5*t/mass, tspan, y0);
plot(t,y,’-o’)
formatSpec = ‘The next element of the Y array is equal to %6.4f at %6.4.’;
fprintf (formatSpec,y(end,:),t(end,:));
pause;
endI’m having trouble with the following code. I’m trying to test it to get it to produce the final value as it proceeds through the count and increments the count, but it isn’t working. It won’t go past the first increment. I’m new to Matlab (once again). Can anyone assist me?
handle=[];
%Initial Conditions
pn0 = 0.0; %Initial north position
pe0 = 0.0; %initial east position
pd0 = -100.0; %initial east position
u0 =25.0; %initial velocity along body x-axis
v0 = 0.0; %initial velocity along body y-axis
w0 = 0.0; %initial velocity along body z-axis
phi0 = 0.0; %initial roll angle
theta0 = 0.0; %initial pitch angle
psi0 = 0.0; %initial yaw rate
l0 = 0; %initial moment about ib axis
m0 = 0; %initial moment about jb axis
n0 = 0; %initial moment about kb axis
p0 = 0; %initial roll rate along ib in Fb
q0 = 0; %initial pitch rate along jb in Fb
r0 = 0; %initial yaw rate along kb in Fb
Va0 = (u0^2 + v0^2 + w0^2)^0.5; %initial velocity
%Initial forces producing acceleration – fx, fy, fz
fx = 0; %Force in the ib direction.
fy = 0; %Force in the jb direciton.
fz = 0; %Force in the kb direction.
%Plane is initially aligned so that ib,jb, and kb
%correspond to x, y, z.
%Physical Parameters
mass = 11; % kg
Jx = 0.8244; %kg m^2
Jy = 1.135;
Jz = 1.759;
Jxz = 0.1204;
S_wing = 0.55;
b = 2.8956;
c = 0.18994;
Sprop = 0.2027;
rho = 1.2682;
e = 0.9;
AR = (b^2)/S_wing;
gravity = 9.81;
%Gamma Values
G = Jx * Jz – (Jxz^2);
G1 = (Jxz * (Jx – Jy + Jz))/ G ;
G2 = (Jz * (Jz – Jy) + (Jxz^2))/ G;
G3 = Jz / G;
G4 = Jxz / G;
G5 = (Jz – Jx) / Jy;
G6 = Jxz / Jy;
G7 = ((Jx – Jy) * Jx + (Jxz ^ 2)) / G;
G8 = Jx / G;
%Establish the parameters to pass to the subroutines
p = p0;
q = q0;
r = r0;
l = l0;
m = m0;
n = n0;
u = u0;
v = v0;
w = w0;
phi = phi0;
theta = theta0;
psi = psi0;
dt = 0.1;
fxone = fx;
fyone = fy;
fzone = fz;
fxtwo = 0;
fytwo = 0;
fztwo = 0;
n=0;
numsteps=100;
total_time = 100; % total simulation time in seconds
time_step = 0.1; % time step in seconds
num_steps = total_time / time_step; % number of steps
for count = 1:numsteps
clc;
clear all;
%Runge Kutta 4 attempt;
%fx = 5*t/mass
r=0
v=0;
q=0;
w=0;
mass = 10;
tstart = (count-1)*time_step;
tstop = tstart + 0.01;
tspan = [tstart,0.01,tstop];
y0=0.0;
[t,y]=ode45(@(t,y) (r*v-q*w)+5*t/mass, tspan, y0);
plot(t,y,’-o’)
formatSpec = ‘The next element of the Y array is equal to %6.4f at %6.4.’;
fprintf (formatSpec,y(end,:),t(end,:));
pause;
end I’m having trouble with the following code. I’m trying to test it to get it to produce the final value as it proceeds through the count and increments the count, but it isn’t working. It won’t go past the first increment. I’m new to Matlab (once again). Can anyone assist me?
handle=[];
%Initial Conditions
pn0 = 0.0; %Initial north position
pe0 = 0.0; %initial east position
pd0 = -100.0; %initial east position
u0 =25.0; %initial velocity along body x-axis
v0 = 0.0; %initial velocity along body y-axis
w0 = 0.0; %initial velocity along body z-axis
phi0 = 0.0; %initial roll angle
theta0 = 0.0; %initial pitch angle
psi0 = 0.0; %initial yaw rate
l0 = 0; %initial moment about ib axis
m0 = 0; %initial moment about jb axis
n0 = 0; %initial moment about kb axis
p0 = 0; %initial roll rate along ib in Fb
q0 = 0; %initial pitch rate along jb in Fb
r0 = 0; %initial yaw rate along kb in Fb
Va0 = (u0^2 + v0^2 + w0^2)^0.5; %initial velocity
%Initial forces producing acceleration – fx, fy, fz
fx = 0; %Force in the ib direction.
fy = 0; %Force in the jb direciton.
fz = 0; %Force in the kb direction.
%Plane is initially aligned so that ib,jb, and kb
%correspond to x, y, z.
%Physical Parameters
mass = 11; % kg
Jx = 0.8244; %kg m^2
Jy = 1.135;
Jz = 1.759;
Jxz = 0.1204;
S_wing = 0.55;
b = 2.8956;
c = 0.18994;
Sprop = 0.2027;
rho = 1.2682;
e = 0.9;
AR = (b^2)/S_wing;
gravity = 9.81;
%Gamma Values
G = Jx * Jz – (Jxz^2);
G1 = (Jxz * (Jx – Jy + Jz))/ G ;
G2 = (Jz * (Jz – Jy) + (Jxz^2))/ G;
G3 = Jz / G;
G4 = Jxz / G;
G5 = (Jz – Jx) / Jy;
G6 = Jxz / Jy;
G7 = ((Jx – Jy) * Jx + (Jxz ^ 2)) / G;
G8 = Jx / G;
%Establish the parameters to pass to the subroutines
p = p0;
q = q0;
r = r0;
l = l0;
m = m0;
n = n0;
u = u0;
v = v0;
w = w0;
phi = phi0;
theta = theta0;
psi = psi0;
dt = 0.1;
fxone = fx;
fyone = fy;
fzone = fz;
fxtwo = 0;
fytwo = 0;
fztwo = 0;
n=0;
numsteps=100;
total_time = 100; % total simulation time in seconds
time_step = 0.1; % time step in seconds
num_steps = total_time / time_step; % number of steps
for count = 1:numsteps
clc;
clear all;
%Runge Kutta 4 attempt;
%fx = 5*t/mass
r=0
v=0;
q=0;
w=0;
mass = 10;
tstart = (count-1)*time_step;
tstop = tstart + 0.01;
tspan = [tstart,0.01,tstop];
y0=0.0;
[t,y]=ode45(@(t,y) (r*v-q*w)+5*t/mass, tspan, y0);
plot(t,y,’-o’)
formatSpec = ‘The next element of the Y array is equal to %6.4f at %6.4.’;
fprintf (formatSpec,y(end,:),t(end,:));
pause;
end runge kutta MATLAB Answers — New Questions
Generated code (Embedded Coder) for Mod block generates expensive function call to rt_modf
Using the built in math function block for the mod operation generates an expensive function call in the generated code.
I am using floating points and the desire is just to produce fmodf() as the result of code generation.
Anyone have any ideas? there do not seem to be any settings for this block related to CodeGenUsing the built in math function block for the mod operation generates an expensive function call in the generated code.
I am using floating points and the desire is just to produce fmodf() as the result of code generation.
Anyone have any ideas? there do not seem to be any settings for this block related to CodeGen Using the built in math function block for the mod operation generates an expensive function call in the generated code.
I am using floating points and the desire is just to produce fmodf() as the result of code generation.
Anyone have any ideas? there do not seem to be any settings for this block related to CodeGen modulus, modulo, fmodf, rt_modf, mod MATLAB Answers — New Questions
Limit the number of Radar detections per object to one in Automated driving toolbox
Hi,
I am using the Automated Driving Toolbox to collect radar data and test my algorithm. My algorithm is designed to use only one detection per object. Is there a way to configure this in the Automated Driving Toolbox? I understand that I can limit the total number of detections by radar, but I specifically need one detection per object.Hi,
I am using the Automated Driving Toolbox to collect radar data and test my algorithm. My algorithm is designed to use only one detection per object. Is there a way to configure this in the Automated Driving Toolbox? I understand that I can limit the total number of detections by radar, but I specifically need one detection per object. Hi,
I am using the Automated Driving Toolbox to collect radar data and test my algorithm. My algorithm is designed to use only one detection per object. Is there a way to configure this in the Automated Driving Toolbox? I understand that I can limit the total number of detections by radar, but I specifically need one detection per object. automated driving toolbox, radar MATLAB Answers — New Questions
How do I save the answers from a for loop that solved an equation symbolically?
I am trying to save the answers from a for loop in which I solved an equation symbolically.
T_c = 33.145; %crit temp of hydrogen (K)
P_c = 1.3e6; %crit pressure (Pa)
R = 8.314472; %universal gas constant (J/(mol*K)
a = (0.427487*(R^2)*(T_c^2.5))/P_c;
b = (0.08662*R*T_c)/P_c;
x = 0.000051473700293409386773440257598528; %V_m
for P = 2e6:2e6:70e6
syms T_g
eqn = ((8.314472*T_g)/(x-b)) – (a/(sqrt(T_g)*x*(x+b))) == P;
solx = solve(eqn,T_g,"Real",true);
solx = vpa(solx);
end
With this code, I only have the final answer.
I tried using the code below to save the answers from the for loop, but I could not save them and got the answer in the screenshot.
k=0;
for P = 2e6:2e6:70e6
k=k+1;
syms T_g
eqn = ((8.314472*T_g)/(x-b)) – (a/(sqrt(T_g)*x*(x+b))) == P;
solx = solve(eqn,T_g,"Real",true);
solx = vpa(solx);
T_g(:,k) = solx;
end
Can somebody show how to save the answers from a for loop?I am trying to save the answers from a for loop in which I solved an equation symbolically.
T_c = 33.145; %crit temp of hydrogen (K)
P_c = 1.3e6; %crit pressure (Pa)
R = 8.314472; %universal gas constant (J/(mol*K)
a = (0.427487*(R^2)*(T_c^2.5))/P_c;
b = (0.08662*R*T_c)/P_c;
x = 0.000051473700293409386773440257598528; %V_m
for P = 2e6:2e6:70e6
syms T_g
eqn = ((8.314472*T_g)/(x-b)) – (a/(sqrt(T_g)*x*(x+b))) == P;
solx = solve(eqn,T_g,"Real",true);
solx = vpa(solx);
end
With this code, I only have the final answer.
I tried using the code below to save the answers from the for loop, but I could not save them and got the answer in the screenshot.
k=0;
for P = 2e6:2e6:70e6
k=k+1;
syms T_g
eqn = ((8.314472*T_g)/(x-b)) – (a/(sqrt(T_g)*x*(x+b))) == P;
solx = solve(eqn,T_g,"Real",true);
solx = vpa(solx);
T_g(:,k) = solx;
end
Can somebody show how to save the answers from a for loop? I am trying to save the answers from a for loop in which I solved an equation symbolically.
T_c = 33.145; %crit temp of hydrogen (K)
P_c = 1.3e6; %crit pressure (Pa)
R = 8.314472; %universal gas constant (J/(mol*K)
a = (0.427487*(R^2)*(T_c^2.5))/P_c;
b = (0.08662*R*T_c)/P_c;
x = 0.000051473700293409386773440257598528; %V_m
for P = 2e6:2e6:70e6
syms T_g
eqn = ((8.314472*T_g)/(x-b)) – (a/(sqrt(T_g)*x*(x+b))) == P;
solx = solve(eqn,T_g,"Real",true);
solx = vpa(solx);
end
With this code, I only have the final answer.
I tried using the code below to save the answers from the for loop, but I could not save them and got the answer in the screenshot.
k=0;
for P = 2e6:2e6:70e6
k=k+1;
syms T_g
eqn = ((8.314472*T_g)/(x-b)) – (a/(sqrt(T_g)*x*(x+b))) == P;
solx = solve(eqn,T_g,"Real",true);
solx = vpa(solx);
T_g(:,k) = solx;
end
Can somebody show how to save the answers from a for loop? for loop, symbolic MATLAB Answers — New Questions
C++ code generation: is it possible to put struct declaration in a namespace?
Hello,
I am generating C++ code using Embedded Coder in v2021b. I am able to put the generated class in my chosen namespace via the Code Interface dialog:
But in my model i am using various buses, which are translated in C++ structs, which in turn reside in the global namespace.
Is there a way to specify a namespace for these structs too?Hello,
I am generating C++ code using Embedded Coder in v2021b. I am able to put the generated class in my chosen namespace via the Code Interface dialog:
But in my model i am using various buses, which are translated in C++ structs, which in turn reside in the global namespace.
Is there a way to specify a namespace for these structs too? Hello,
I am generating C++ code using Embedded Coder in v2021b. I am able to put the generated class in my chosen namespace via the Code Interface dialog:
But in my model i am using various buses, which are translated in C++ structs, which in turn reside in the global namespace.
Is there a way to specify a namespace for these structs too? c++, embedded coder, simulink MATLAB Answers — New Questions
Saving class objects in array suddenly tanking performance
So, I have this tool I’ve developed to do some radar simulations. One small part of it is I use this class just for bundling and passing around detection data instead of a struct:
classdef Detection
% Data holder for a radar detection
properties
time (1,1) double
snr (1,1) double
raer (1,4) double
sigmas (1,4) double
end
methods
function obj = Detection(time,snr,raer,sigmas)
if nargin > 0 % Allow no args constructor to be called to make empty detections
obj.time = time;
obj.snr = snr;
obj.raer = raer;
obj.sigmas = sigmas;
end
end
end
end
These get created in one handle class then passed off to another that saves data on a given target. In that object, I save them into a (pre-allocated* array):
this.detections(i) = det;
After making some code changes yesterday, suddenly this one line went from being trivial computationally to 70% of the run-time of a basic sim run when profiled, more than tripling the run time of said sim from ~1s to ~3s for 761 detections saved. I can’t figure out how to pull out any more details about what’s suddenly making a simple operation like that so slow, or how to work around it. I’ve run into some weird behavior like this in the past when saving simple data holder objects caused bizarre performance issues, but usually I could tweak something or find a work around, here I’m just stumped as to what caused it because I didn’t even change anything about the object or how they’re saved.
*Specifically, they start with a base size and then if the sim runs long enough to outstrip that I start doubling the data arrays, just thought I’d add that in case there’s some weird potential behavior there.
Edit: I tried making this class and the Dwell class (other one mentioned in comments) handles, and that seems to have alleviated the problem (although still seems noticeably slower than saving structs), but I’m curious as to why saving value classes is seemingly so slow.So, I have this tool I’ve developed to do some radar simulations. One small part of it is I use this class just for bundling and passing around detection data instead of a struct:
classdef Detection
% Data holder for a radar detection
properties
time (1,1) double
snr (1,1) double
raer (1,4) double
sigmas (1,4) double
end
methods
function obj = Detection(time,snr,raer,sigmas)
if nargin > 0 % Allow no args constructor to be called to make empty detections
obj.time = time;
obj.snr = snr;
obj.raer = raer;
obj.sigmas = sigmas;
end
end
end
end
These get created in one handle class then passed off to another that saves data on a given target. In that object, I save them into a (pre-allocated* array):
this.detections(i) = det;
After making some code changes yesterday, suddenly this one line went from being trivial computationally to 70% of the run-time of a basic sim run when profiled, more than tripling the run time of said sim from ~1s to ~3s for 761 detections saved. I can’t figure out how to pull out any more details about what’s suddenly making a simple operation like that so slow, or how to work around it. I’ve run into some weird behavior like this in the past when saving simple data holder objects caused bizarre performance issues, but usually I could tweak something or find a work around, here I’m just stumped as to what caused it because I didn’t even change anything about the object or how they’re saved.
*Specifically, they start with a base size and then if the sim runs long enough to outstrip that I start doubling the data arrays, just thought I’d add that in case there’s some weird potential behavior there.
Edit: I tried making this class and the Dwell class (other one mentioned in comments) handles, and that seems to have alleviated the problem (although still seems noticeably slower than saving structs), but I’m curious as to why saving value classes is seemingly so slow. So, I have this tool I’ve developed to do some radar simulations. One small part of it is I use this class just for bundling and passing around detection data instead of a struct:
classdef Detection
% Data holder for a radar detection
properties
time (1,1) double
snr (1,1) double
raer (1,4) double
sigmas (1,4) double
end
methods
function obj = Detection(time,snr,raer,sigmas)
if nargin > 0 % Allow no args constructor to be called to make empty detections
obj.time = time;
obj.snr = snr;
obj.raer = raer;
obj.sigmas = sigmas;
end
end
end
end
These get created in one handle class then passed off to another that saves data on a given target. In that object, I save them into a (pre-allocated* array):
this.detections(i) = det;
After making some code changes yesterday, suddenly this one line went from being trivial computationally to 70% of the run-time of a basic sim run when profiled, more than tripling the run time of said sim from ~1s to ~3s for 761 detections saved. I can’t figure out how to pull out any more details about what’s suddenly making a simple operation like that so slow, or how to work around it. I’ve run into some weird behavior like this in the past when saving simple data holder objects caused bizarre performance issues, but usually I could tweak something or find a work around, here I’m just stumped as to what caused it because I didn’t even change anything about the object or how they’re saved.
*Specifically, they start with a base size and then if the sim runs long enough to outstrip that I start doubling the data arrays, just thought I’d add that in case there’s some weird potential behavior there.
Edit: I tried making this class and the Dwell class (other one mentioned in comments) handles, and that seems to have alleviated the problem (although still seems noticeably slower than saving structs), but I’m curious as to why saving value classes is seemingly so slow. class, objects, performance, arrays MATLAB Answers — New Questions
Not able to run simulations using Rapid accelerator
Running the example provide by Mathworks to simulate in rapid accelerator (sldemo_bounce) I got the following error message:
Top Model Build
1
Elapsed: 3 sec
### Building the rapid accelerator target for model: sldemo_bounce "INGWROOTbin/gcc" -c -fwrapv -m64 -O0 -DCLASSIC_INTERFACE=1 -DALLOCATIONFCN=0 -DONESTEPFCN=0 -DTERMFCN=1 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DEXT_MODE -DIS_RAPID_ACCEL -DTGTCONN -DIS_SIM_TARGET -DNRT -DRSIM_PARAMETER_LOADING -DRSIM_WITH_SL_SOLVER -DENABLE_SLEXEC_SSBRIDGE=1 -DMODEL_HAS_DYNAMICALLY_LOADED_SFCNS=0 -DON_TARGET_WAIT_FOR_START=0 -DTID01EQ=0 -DMODEL=sldemo_bounce -DNUMST=2 -DNCSTATES=2 -DHAVESTDIO @sldemo_bounce_comp.rsp -o "rt_logging_simtarget.obj" "C:/PROGRA~1/MATLAB/R2021a/rtw/c/src/rt_logging_simtarget.c" The system cannot find the path specified. gmake: *** [rt_logging_simtarget.obj] Error 1 The make command returned an error of 2 ### Build procedure for sldemo_bounce aborted due to an error.
Build Summary
1
Elapsed: 0.2 sec
Top model rapid accelerator targets built: Model Action Rebuild Reason ========================================================================= sldemo_bounce Failed Code generation information file does not exist. 0 of 1 models built (0 models already up to date) Build duration: 0h 0m 3.238s
Unable to build a standalone executable to simulate the model ‘sldemo_bounce’ in rapid accelerator mode.
Caused by:
Error(s) encountered while building "sldemo_bounce"
to run the simulation in rapid accelerator do I need the real time workshop tools license?
Regards
EduardoRunning the example provide by Mathworks to simulate in rapid accelerator (sldemo_bounce) I got the following error message:
Top Model Build
1
Elapsed: 3 sec
### Building the rapid accelerator target for model: sldemo_bounce "INGWROOTbin/gcc" -c -fwrapv -m64 -O0 -DCLASSIC_INTERFACE=1 -DALLOCATIONFCN=0 -DONESTEPFCN=0 -DTERMFCN=1 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DEXT_MODE -DIS_RAPID_ACCEL -DTGTCONN -DIS_SIM_TARGET -DNRT -DRSIM_PARAMETER_LOADING -DRSIM_WITH_SL_SOLVER -DENABLE_SLEXEC_SSBRIDGE=1 -DMODEL_HAS_DYNAMICALLY_LOADED_SFCNS=0 -DON_TARGET_WAIT_FOR_START=0 -DTID01EQ=0 -DMODEL=sldemo_bounce -DNUMST=2 -DNCSTATES=2 -DHAVESTDIO @sldemo_bounce_comp.rsp -o "rt_logging_simtarget.obj" "C:/PROGRA~1/MATLAB/R2021a/rtw/c/src/rt_logging_simtarget.c" The system cannot find the path specified. gmake: *** [rt_logging_simtarget.obj] Error 1 The make command returned an error of 2 ### Build procedure for sldemo_bounce aborted due to an error.
Build Summary
1
Elapsed: 0.2 sec
Top model rapid accelerator targets built: Model Action Rebuild Reason ========================================================================= sldemo_bounce Failed Code generation information file does not exist. 0 of 1 models built (0 models already up to date) Build duration: 0h 0m 3.238s
Unable to build a standalone executable to simulate the model ‘sldemo_bounce’ in rapid accelerator mode.
Caused by:
Error(s) encountered while building "sldemo_bounce"
to run the simulation in rapid accelerator do I need the real time workshop tools license?
Regards
Eduardo Running the example provide by Mathworks to simulate in rapid accelerator (sldemo_bounce) I got the following error message:
Top Model Build
1
Elapsed: 3 sec
### Building the rapid accelerator target for model: sldemo_bounce "INGWROOTbin/gcc" -c -fwrapv -m64 -O0 -DCLASSIC_INTERFACE=1 -DALLOCATIONFCN=0 -DONESTEPFCN=0 -DTERMFCN=1 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DEXT_MODE -DIS_RAPID_ACCEL -DTGTCONN -DIS_SIM_TARGET -DNRT -DRSIM_PARAMETER_LOADING -DRSIM_WITH_SL_SOLVER -DENABLE_SLEXEC_SSBRIDGE=1 -DMODEL_HAS_DYNAMICALLY_LOADED_SFCNS=0 -DON_TARGET_WAIT_FOR_START=0 -DTID01EQ=0 -DMODEL=sldemo_bounce -DNUMST=2 -DNCSTATES=2 -DHAVESTDIO @sldemo_bounce_comp.rsp -o "rt_logging_simtarget.obj" "C:/PROGRA~1/MATLAB/R2021a/rtw/c/src/rt_logging_simtarget.c" The system cannot find the path specified. gmake: *** [rt_logging_simtarget.obj] Error 1 The make command returned an error of 2 ### Build procedure for sldemo_bounce aborted due to an error.
Build Summary
1
Elapsed: 0.2 sec
Top model rapid accelerator targets built: Model Action Rebuild Reason ========================================================================= sldemo_bounce Failed Code generation information file does not exist. 0 of 1 models built (0 models already up to date) Build duration: 0h 0m 3.238s
Unable to build a standalone executable to simulate the model ‘sldemo_bounce’ in rapid accelerator mode.
Caused by:
Error(s) encountered while building "sldemo_bounce"
to run the simulation in rapid accelerator do I need the real time workshop tools license?
Regards
Eduardo simulink, rapid accelerator MATLAB Answers — New Questions
Can the output of plsregress be used to calculate Q residuals and T2 for new X data
Assume we have spectral data xcal, ycal, xval, yval where
xcal is mxn : m spectra, or observations, of a sample, n wavelengths per spectrum
ycal is mx1 : m concentrations of the sample corresponding to the m observations in xcal
xval is 1xn : 1 new spetrum or new observation of the sample (ie, not a member of xcal)
yval is 1×1 : 1 new concentration of the sample corresponding to the observation in xval
assuming m>n and ncomp<n and xcal0 is xcal with its mean subtracted,
xcal0 = xcal – ones(m,1)*mean(xcal)
[XL,YL,XS,YS,BETA,PCTVAR,MSE,STATS] = PLSREGRESS(xcal,ycal,ncomp);
Can be used to compute Q residuals, or the rowwise sum of squares of the STATS.XResiduals matrix
and
STATS.T2, is the Hotelling T^2 value
for each of the m observations in xcal
Q residuals and T2 values can be used to determine if the observations in xcal are outliers
Can the outputs of plsregress as described above be used to compute a Q residual and a T^2 value for the single observation in xval to determine if it seems to be an outlier with respect to xcal?Assume we have spectral data xcal, ycal, xval, yval where
xcal is mxn : m spectra, or observations, of a sample, n wavelengths per spectrum
ycal is mx1 : m concentrations of the sample corresponding to the m observations in xcal
xval is 1xn : 1 new spetrum or new observation of the sample (ie, not a member of xcal)
yval is 1×1 : 1 new concentration of the sample corresponding to the observation in xval
assuming m>n and ncomp<n and xcal0 is xcal with its mean subtracted,
xcal0 = xcal – ones(m,1)*mean(xcal)
[XL,YL,XS,YS,BETA,PCTVAR,MSE,STATS] = PLSREGRESS(xcal,ycal,ncomp);
Can be used to compute Q residuals, or the rowwise sum of squares of the STATS.XResiduals matrix
and
STATS.T2, is the Hotelling T^2 value
for each of the m observations in xcal
Q residuals and T2 values can be used to determine if the observations in xcal are outliers
Can the outputs of plsregress as described above be used to compute a Q residual and a T^2 value for the single observation in xval to determine if it seems to be an outlier with respect to xcal? Assume we have spectral data xcal, ycal, xval, yval where
xcal is mxn : m spectra, or observations, of a sample, n wavelengths per spectrum
ycal is mx1 : m concentrations of the sample corresponding to the m observations in xcal
xval is 1xn : 1 new spetrum or new observation of the sample (ie, not a member of xcal)
yval is 1×1 : 1 new concentration of the sample corresponding to the observation in xval
assuming m>n and ncomp<n and xcal0 is xcal with its mean subtracted,
xcal0 = xcal – ones(m,1)*mean(xcal)
[XL,YL,XS,YS,BETA,PCTVAR,MSE,STATS] = PLSREGRESS(xcal,ycal,ncomp);
Can be used to compute Q residuals, or the rowwise sum of squares of the STATS.XResiduals matrix
and
STATS.T2, is the Hotelling T^2 value
for each of the m observations in xcal
Q residuals and T2 values can be used to determine if the observations in xcal are outliers
Can the outputs of plsregress as described above be used to compute a Q residual and a T^2 value for the single observation in xval to determine if it seems to be an outlier with respect to xcal? plsregress q residuals, plsregress t2, plsregress outlier new data MATLAB Answers — New Questions
Convert string of nested field names to variable without eval?
Sorry if this is answered elsewhere, It wasn’t obvious to me from searching the archives that this exact question has been posed before.
I am parsing XML files using the function in File Exchange xml2struct (https://www.mathworks.com/matlabcentral/fileexchange/28518-xml2struct) which is a great tool, BTW.
As you might expected, the output is a nested structure, and depending on the input file, the field names and complexity of the structures are highly variable.
I am searching through theses structures to find a particular field of interest:
S.Data.Configuration.FieldofInterest
but in another file, that field might be on a completely different branch or level:
S2.Data.Nested.Field.FieldofInterest
I can generate list of strings with all the field names which I can parse to find the field of interest. But then I have some strings like this:
fnlist = ‘S.Data.Configuration.FieldofInterest’;
fnlist2 = ‘S2.Data.Nested.Field.FieldofInterest’;
If I want to extract the data from the fields of interest, the only way I know how to do this is to use eval:
output = eval(fnlist);
I’m not a fan of the eval functions because they make it very hard to debug code and diagnose problems if the string gets malformed.
I’d like to use dynamic field names like S.(name1).(name2).(name3), etc., but unless you know a priori the data structure and how many levels in your target field is (which I will not), this isn’t possible.
Is there another alternative besides eval? Thanks in advance.Sorry if this is answered elsewhere, It wasn’t obvious to me from searching the archives that this exact question has been posed before.
I am parsing XML files using the function in File Exchange xml2struct (https://www.mathworks.com/matlabcentral/fileexchange/28518-xml2struct) which is a great tool, BTW.
As you might expected, the output is a nested structure, and depending on the input file, the field names and complexity of the structures are highly variable.
I am searching through theses structures to find a particular field of interest:
S.Data.Configuration.FieldofInterest
but in another file, that field might be on a completely different branch or level:
S2.Data.Nested.Field.FieldofInterest
I can generate list of strings with all the field names which I can parse to find the field of interest. But then I have some strings like this:
fnlist = ‘S.Data.Configuration.FieldofInterest’;
fnlist2 = ‘S2.Data.Nested.Field.FieldofInterest’;
If I want to extract the data from the fields of interest, the only way I know how to do this is to use eval:
output = eval(fnlist);
I’m not a fan of the eval functions because they make it very hard to debug code and diagnose problems if the string gets malformed.
I’d like to use dynamic field names like S.(name1).(name2).(name3), etc., but unless you know a priori the data structure and how many levels in your target field is (which I will not), this isn’t possible.
Is there another alternative besides eval? Thanks in advance. Sorry if this is answered elsewhere, It wasn’t obvious to me from searching the archives that this exact question has been posed before.
I am parsing XML files using the function in File Exchange xml2struct (https://www.mathworks.com/matlabcentral/fileexchange/28518-xml2struct) which is a great tool, BTW.
As you might expected, the output is a nested structure, and depending on the input file, the field names and complexity of the structures are highly variable.
I am searching through theses structures to find a particular field of interest:
S.Data.Configuration.FieldofInterest
but in another file, that field might be on a completely different branch or level:
S2.Data.Nested.Field.FieldofInterest
I can generate list of strings with all the field names which I can parse to find the field of interest. But then I have some strings like this:
fnlist = ‘S.Data.Configuration.FieldofInterest’;
fnlist2 = ‘S2.Data.Nested.Field.FieldofInterest’;
If I want to extract the data from the fields of interest, the only way I know how to do this is to use eval:
output = eval(fnlist);
I’m not a fan of the eval functions because they make it very hard to debug code and diagnose problems if the string gets malformed.
I’d like to use dynamic field names like S.(name1).(name2).(name3), etc., but unless you know a priori the data structure and how many levels in your target field is (which I will not), this isn’t possible.
Is there another alternative besides eval? Thanks in advance. struct, eval, field names MATLAB Answers — New Questions
Can anyone please help ?
im trying to compute the steady solutions for the stream function and scalar vorticity for a 2d flow around an infinite cylinder at RE = 10
here is the question:
Here is the code:
function [psi, omega] = flow_around_cylinder_steady
Re=10;
%%%%% define the grid %%%%%
n=101; m=101; % number of grid points
N=n-1; M=m-1; % number of grid intervals
h=pi/M; % grid spacing based on theta variable
xi=(0:N)*h; theta=(0:M)*h; % xi and theta variables on the grid
%%%%% Initialize the flow fields %%%%%
psi=zeros(n,m);
omega=zeros(n,m);
psi(n,:)=exp(xi(n)) * sin(theta(:));
%%%%% Set relax params, tol, extra variables %%%%%
r_psi=1.8
r_omega=0.9
delta=1.e-08; % error tolerance
error=2*delta; % initialize error variable
%%%%% Add any additional variable definitions here %%%%%
…
…
%%%%% Main SOR Loop %%%%%
while (error > delta)
psi_old = psi; omega_old = omega;
for i=2:n-1
for j=2:m-1
psi(i,j)=exp(xi(i)) * sin(theta(j));
end
end
error_psi=max(abs(psi(:)-psi_old(:)));
omega(1,:)= (psi(3,j) – 8*psi(2,j)) * 1/(2*h^2);
for i=2:n-1
for j=2:m-1
omega_old(1,j)= (psi(3,j) – 8*psi(2,j)) * 1/(2*h^2);
end
end
error_omega=max(abs(omega(:)-omega_old(:)));
error=max(error_psi, error_omega);
end
plot_Re10(psi);
The code to call the function is:
[psi, omega] = flow_around_cylinder_steady;
But i get this:
The server timed out while running your solution. Potential reasons include inefficient code, an infinite loop, and excessive output. Try to improve your solution.
is there any way to improve it ?im trying to compute the steady solutions for the stream function and scalar vorticity for a 2d flow around an infinite cylinder at RE = 10
here is the question:
Here is the code:
function [psi, omega] = flow_around_cylinder_steady
Re=10;
%%%%% define the grid %%%%%
n=101; m=101; % number of grid points
N=n-1; M=m-1; % number of grid intervals
h=pi/M; % grid spacing based on theta variable
xi=(0:N)*h; theta=(0:M)*h; % xi and theta variables on the grid
%%%%% Initialize the flow fields %%%%%
psi=zeros(n,m);
omega=zeros(n,m);
psi(n,:)=exp(xi(n)) * sin(theta(:));
%%%%% Set relax params, tol, extra variables %%%%%
r_psi=1.8
r_omega=0.9
delta=1.e-08; % error tolerance
error=2*delta; % initialize error variable
%%%%% Add any additional variable definitions here %%%%%
…
…
%%%%% Main SOR Loop %%%%%
while (error > delta)
psi_old = psi; omega_old = omega;
for i=2:n-1
for j=2:m-1
psi(i,j)=exp(xi(i)) * sin(theta(j));
end
end
error_psi=max(abs(psi(:)-psi_old(:)));
omega(1,:)= (psi(3,j) – 8*psi(2,j)) * 1/(2*h^2);
for i=2:n-1
for j=2:m-1
omega_old(1,j)= (psi(3,j) – 8*psi(2,j)) * 1/(2*h^2);
end
end
error_omega=max(abs(omega(:)-omega_old(:)));
error=max(error_psi, error_omega);
end
plot_Re10(psi);
The code to call the function is:
[psi, omega] = flow_around_cylinder_steady;
But i get this:
The server timed out while running your solution. Potential reasons include inefficient code, an infinite loop, and excessive output. Try to improve your solution.
is there any way to improve it ? im trying to compute the steady solutions for the stream function and scalar vorticity for a 2d flow around an infinite cylinder at RE = 10
here is the question:
Here is the code:
function [psi, omega] = flow_around_cylinder_steady
Re=10;
%%%%% define the grid %%%%%
n=101; m=101; % number of grid points
N=n-1; M=m-1; % number of grid intervals
h=pi/M; % grid spacing based on theta variable
xi=(0:N)*h; theta=(0:M)*h; % xi and theta variables on the grid
%%%%% Initialize the flow fields %%%%%
psi=zeros(n,m);
omega=zeros(n,m);
psi(n,:)=exp(xi(n)) * sin(theta(:));
%%%%% Set relax params, tol, extra variables %%%%%
r_psi=1.8
r_omega=0.9
delta=1.e-08; % error tolerance
error=2*delta; % initialize error variable
%%%%% Add any additional variable definitions here %%%%%
…
…
%%%%% Main SOR Loop %%%%%
while (error > delta)
psi_old = psi; omega_old = omega;
for i=2:n-1
for j=2:m-1
psi(i,j)=exp(xi(i)) * sin(theta(j));
end
end
error_psi=max(abs(psi(:)-psi_old(:)));
omega(1,:)= (psi(3,j) – 8*psi(2,j)) * 1/(2*h^2);
for i=2:n-1
for j=2:m-1
omega_old(1,j)= (psi(3,j) – 8*psi(2,j)) * 1/(2*h^2);
end
end
error_omega=max(abs(omega(:)-omega_old(:)));
error=max(error_psi, error_omega);
end
plot_Re10(psi);
The code to call the function is:
[psi, omega] = flow_around_cylinder_steady;
But i get this:
The server timed out while running your solution. Potential reasons include inefficient code, an infinite loop, and excessive output. Try to improve your solution.
is there any way to improve it ? steady flow at re = 10, homework, assignment, exam question, cylinder MATLAB Answers — New Questions
How to generate a time signal from spectrum
Hello,
I’m working on spectrum comes from sea wave data.
I have a JONSWAP spectrum and I need to generate a signal in time domain to fed my numerical model of a floating body, can anybody suggest me how do it.Hello,
I’m working on spectrum comes from sea wave data.
I have a JONSWAP spectrum and I need to generate a signal in time domain to fed my numerical model of a floating body, can anybody suggest me how do it. Hello,
I’m working on spectrum comes from sea wave data.
I have a JONSWAP spectrum and I need to generate a signal in time domain to fed my numerical model of a floating body, can anybody suggest me how do it. signal, spectrum MATLAB Answers — New Questions
Hi I have a query I removed the harmonic to preserve the fundamental but still fundamental at 1MHz is also filtered can anyone tell m e.
% Load the frequency domain data
folder = ‘C:UsershaneuOneDrive바탕 화면dateNew folder (2)’;
filename = ‘270mvp.csv’;
data = readtable(fullfile(folder, filename));
% Extract frequency and FFT amplitude (assumed to be in dB)
f = table2array(data(3:end, 3)); % Frequency data (in Hz)
x_dB = table2array(data(3:end, 4)); % FFT amplitude data in dB
% Number of points in the FFT
N = length(x_dB);
% Compute the sampling frequency (fs)
% Assuming that your frequency axis (f) is spaced evenly
df = f(2) – f(1); % Frequency resolution
fs = N * df; % Sampling frequency
% Convert the amplitude from dB to linear scale
x_linear = 10.^(x_dB / 20);
% Compute the Power Spectral Density (PSD)
pxx = (x_linear.^2) / (fs * N);
% Convert PSD to dB/Hz
pxx_dBHz = 10 * log10(pxx);
% Fundamental frequency
f0 = 1e6; % 1 MHz
% Identify harmonic frequencies
harmonics = f0 * (1:floor(max(f)/f0));
% Remove harmonics from PSD
pxx_dBHz_filtered = pxx_dBHz; % Copy original PSD
for k = 1:length(harmonics)
harmonic_freq = harmonics(k);
[~, idx] = min(abs(f – harmonic_freq)); % Find the closest frequency index
pxx_dBHz_filtered(idx) = -Inf; % Set PSD of harmonics to -Inf (effectively removing)
end
% Plot the original Power Spectral Density (PSD)
figure;
subplot(2, 1, 1);
plot(f/1e6, pxx_dBHz);
xlabel(‘Frequency (MHz)’);
ylabel(‘PSD (dB/Hz)’);
title(‘Original Power Spectral Density (PSD)’);
% Plot the filtered Power Spectral Density (PSD)
subplot(2, 1, 2);
plot(f/1e6, pxx_dBHz_filtered);
xlabel(‘Frequency (MHz)’);
ylabel(‘PSD (dB/Hz)’);
title(‘Filtered Power Spectral Density (PSD)’);
% Highlight fundamental frequency in the plot
hold on;
plot(f0/1e6, pxx_dBHz_filtered(abs(f – f0) < df), ‘ro’, ‘MarkerSize’, 8, ‘LineWidth’, 2);
legend(‘Filtered PSD’, ‘Fundamental Frequency’);% Load the frequency domain data
folder = ‘C:UsershaneuOneDrive바탕 화면dateNew folder (2)’;
filename = ‘270mvp.csv’;
data = readtable(fullfile(folder, filename));
% Extract frequency and FFT amplitude (assumed to be in dB)
f = table2array(data(3:end, 3)); % Frequency data (in Hz)
x_dB = table2array(data(3:end, 4)); % FFT amplitude data in dB
% Number of points in the FFT
N = length(x_dB);
% Compute the sampling frequency (fs)
% Assuming that your frequency axis (f) is spaced evenly
df = f(2) – f(1); % Frequency resolution
fs = N * df; % Sampling frequency
% Convert the amplitude from dB to linear scale
x_linear = 10.^(x_dB / 20);
% Compute the Power Spectral Density (PSD)
pxx = (x_linear.^2) / (fs * N);
% Convert PSD to dB/Hz
pxx_dBHz = 10 * log10(pxx);
% Fundamental frequency
f0 = 1e6; % 1 MHz
% Identify harmonic frequencies
harmonics = f0 * (1:floor(max(f)/f0));
% Remove harmonics from PSD
pxx_dBHz_filtered = pxx_dBHz; % Copy original PSD
for k = 1:length(harmonics)
harmonic_freq = harmonics(k);
[~, idx] = min(abs(f – harmonic_freq)); % Find the closest frequency index
pxx_dBHz_filtered(idx) = -Inf; % Set PSD of harmonics to -Inf (effectively removing)
end
% Plot the original Power Spectral Density (PSD)
figure;
subplot(2, 1, 1);
plot(f/1e6, pxx_dBHz);
xlabel(‘Frequency (MHz)’);
ylabel(‘PSD (dB/Hz)’);
title(‘Original Power Spectral Density (PSD)’);
% Plot the filtered Power Spectral Density (PSD)
subplot(2, 1, 2);
plot(f/1e6, pxx_dBHz_filtered);
xlabel(‘Frequency (MHz)’);
ylabel(‘PSD (dB/Hz)’);
title(‘Filtered Power Spectral Density (PSD)’);
% Highlight fundamental frequency in the plot
hold on;
plot(f0/1e6, pxx_dBHz_filtered(abs(f – f0) < df), ‘ro’, ‘MarkerSize’, 8, ‘LineWidth’, 2);
legend(‘Filtered PSD’, ‘Fundamental Frequency’); % Load the frequency domain data
folder = ‘C:UsershaneuOneDrive바탕 화면dateNew folder (2)’;
filename = ‘270mvp.csv’;
data = readtable(fullfile(folder, filename));
% Extract frequency and FFT amplitude (assumed to be in dB)
f = table2array(data(3:end, 3)); % Frequency data (in Hz)
x_dB = table2array(data(3:end, 4)); % FFT amplitude data in dB
% Number of points in the FFT
N = length(x_dB);
% Compute the sampling frequency (fs)
% Assuming that your frequency axis (f) is spaced evenly
df = f(2) – f(1); % Frequency resolution
fs = N * df; % Sampling frequency
% Convert the amplitude from dB to linear scale
x_linear = 10.^(x_dB / 20);
% Compute the Power Spectral Density (PSD)
pxx = (x_linear.^2) / (fs * N);
% Convert PSD to dB/Hz
pxx_dBHz = 10 * log10(pxx);
% Fundamental frequency
f0 = 1e6; % 1 MHz
% Identify harmonic frequencies
harmonics = f0 * (1:floor(max(f)/f0));
% Remove harmonics from PSD
pxx_dBHz_filtered = pxx_dBHz; % Copy original PSD
for k = 1:length(harmonics)
harmonic_freq = harmonics(k);
[~, idx] = min(abs(f – harmonic_freq)); % Find the closest frequency index
pxx_dBHz_filtered(idx) = -Inf; % Set PSD of harmonics to -Inf (effectively removing)
end
% Plot the original Power Spectral Density (PSD)
figure;
subplot(2, 1, 1);
plot(f/1e6, pxx_dBHz);
xlabel(‘Frequency (MHz)’);
ylabel(‘PSD (dB/Hz)’);
title(‘Original Power Spectral Density (PSD)’);
% Plot the filtered Power Spectral Density (PSD)
subplot(2, 1, 2);
plot(f/1e6, pxx_dBHz_filtered);
xlabel(‘Frequency (MHz)’);
ylabel(‘PSD (dB/Hz)’);
title(‘Filtered Power Spectral Density (PSD)’);
% Highlight fundamental frequency in the plot
hold on;
plot(f0/1e6, pxx_dBHz_filtered(abs(f – f0) < df), ‘ro’, ‘MarkerSize’, 8, ‘LineWidth’, 2);
legend(‘Filtered PSD’, ‘Fundamental Frequency’); signal processing, filter MATLAB Answers — New Questions
Mex compiler MinGW64 only, although msvcpp xmls are in the mexopts folder
Hi,
I am having issues – for whatever reason my previous GPU compile for VS studio 2019 and Matlab 2022a got corrupted and now VS studio no longer offers VS 2019 download.
My exact issue is that the mex -setup C++ only finds MinGW64 and not the VS studio code (msvc2022) although it is in the mexopts folder and VS studio 2022 is download (including the manual C++ library installation).
Mathworks has xmls but it seems mex is not robust enough to find them and does not allow for manual addition of compilers (even though the xmls are thoroughly there in win64 folder. Does anyone have any ideas how to compile VS studio 2022 with whatever version of MATLAB that works with it.Hi,
I am having issues – for whatever reason my previous GPU compile for VS studio 2019 and Matlab 2022a got corrupted and now VS studio no longer offers VS 2019 download.
My exact issue is that the mex -setup C++ only finds MinGW64 and not the VS studio code (msvc2022) although it is in the mexopts folder and VS studio 2022 is download (including the manual C++ library installation).
Mathworks has xmls but it seems mex is not robust enough to find them and does not allow for manual addition of compilers (even though the xmls are thoroughly there in win64 folder. Does anyone have any ideas how to compile VS studio 2022 with whatever version of MATLAB that works with it. Hi,
I am having issues – for whatever reason my previous GPU compile for VS studio 2019 and Matlab 2022a got corrupted and now VS studio no longer offers VS 2019 download.
My exact issue is that the mex -setup C++ only finds MinGW64 and not the VS studio code (msvc2022) although it is in the mexopts folder and VS studio 2022 is download (including the manual C++ library installation).
Mathworks has xmls but it seems mex is not robust enough to find them and does not allow for manual addition of compilers (even though the xmls are thoroughly there in win64 folder. Does anyone have any ideas how to compile VS studio 2022 with whatever version of MATLAB that works with it. mex, mex compiler MATLAB Answers — New Questions
textprogress bar in parfor
this used to work in Matlab 2019b and before, to show a progressbar in parfor loop:
%% par pool
[~, output] = system(‘free -b | awk ”/Mem/{print $2}”’);
total_memory = str2double(output);
myCluster = min(ceil(total_memory / 1024^2 / 2 / 1000), round(maxNumCompThreads));
if isempty(gcp(‘nocreate’))
pool=parpool(myCluster,’IdleTimeout’, 604800);%1 week
end
nsim = 50
%% ———————————–
global P;
P = 1;
DataQueue = parallel.pool.DataQueue;
textprogressbar(‘start: ‘);
afterEach(DataQueue, @(ss) textprogressbar(P/nsim*100));
afterEach(DataQueue, @updateP);
parfor i = 1:nsim
send(DataQueue,i);
%someprocess
pause(0.1)
end
textprogressbar(‘ done’)
Now I updated to 2024a Update 4 (24.1.0.2628055). And even though the parloop run just fine, the progressbar is never updated.
Here the code of textprorgessbar I take somewhere from around here:
function textprogressbar(c)
% This function creates a text progress bar. It should be called with a
% STRING argument to initialize and terminate. Otherwise the number correspoding
% to progress in % should be supplied.
% INPUTS: C Either: Text string to initialize or terminate
% Percentage number to show progress
% OUTPUTS: N/A
% Example: Please refer to demo_textprogressbar.m
% Author: Paul Proteus (e-mail: proteus.paul (at) yahoo (dot) com)
% Version: 1.0
% Changes tracker: 29.06.2010 – First version
% Inspired by: http://blogs.mathworks.com/loren/2007/08/01/monitoring-progress-of-a-calculation/
%% Initialization
persistent strCR; % Carriage return pesistent variable
% Vizualization parameters
strPercentageLength = 6; % Length of percentage string (must be >5)
strDotsMaximum = 10; % The total number of dots in a progress bar
%% Main
if isempty(strCR) && ~ischar(c),
% Progress bar must be initialized with a string
error(‘The text progress must be initialized with a string’);
elseif isempty(strCR) && ischar(c),
% Progress bar – initialization
% fprintf(‘%s’,c);
tcprintf(‘green’,c);
strCR = -1;
elseif ~isempty(strCR) && ischar(c),
% Progress bar – termination
strCR = [];
% fprintf([c ‘n’]);
tcprintf(‘red’,[c ‘n’]);
elseif isnumeric(c)
% Progress bar – normal progress
c = floor(c);
percentageOut = [num2str(c) ‘%%’];
percentageOut = [percentageOut repmat(‘ ‘,1,strPercentageLength-length(percentageOut)-1)];
nDots = floor(c/100*strDotsMaximum);
dotOut = [‘[‘ repmat(‘.’,1,nDots) repmat(‘ ‘,1,strDotsMaximum-nDots) ‘]’];
strOut = [percentageOut dotOut];
% Print it on the screen BAR!!!!
if strCR == -1,
% Don’t do carriage return during first run
fprintf(strOut);
% tcprintf(‘yellow’,strOut);
else
% Do it during all the other runs
fprintf([strCR strOut]);
% tcprintf(‘yellow’,[strCR strOut]);
end
% Update carriage return
strCR = repmat(‘b’,1,length(strOut)-1);
else
% Any other unexpected input
error(‘Unsupported argument type’);
end
%%—————————————————
function tcprintf(style, fmatString, varargin)
% Uses ANSI escape codes to print colored output when using MATLAB
% from a terminal. If not running in a terminal, or if called by MATLAB’s
% datatipinfo function, tcprintf reverts to standard printf. The latter is
% desirable if tcprintf is used within an object’s disp() method to avoid
% seeing the ANSI characters here.
%
% The first argument is an style description that consists of space-separated
% words. These words may include:
%
% one of the following colors:
% black, red, green, yellow, blue, purple, cyan, darkGray, lightGray, white
%
% one of the following background colors:
% onBlack, onRed, onGreen, onYellow, onBlue, onPurple, onCyan, onWhite
%
% and any of the following modifiers:
% bright : use the bright (or bold) form of the color, not applicable for
% black, darkGray, lightGray, or white
% underline : draw an underline under each character
% blink : This is a mistake. Please don’t use this ever.
%
% Example:
% tcprintf(‘lightGray onRed underline’, ‘Message: %20sn’, msg);
%
% Author: Dan O’Shea dan at djoshea.com (c) 2012
%
% Released under the open source BSD license
% opensource.org/licenses/bsd-license.php
if nargin < 2 || ~ischar(style) || ~ischar(fmatString)
error(‘Usage: tcprintf(style, fmatString, …)’);
end
% determine if we’re using
usingTerminal = ~usejava(‘desktop’);
% determine if datatipinfo is higher on the stack. If tcprintf
% is used within an object’s disp() method, we don’t want to
% use color in the hover datatip or all you’ll see are ANSI codes.
stack = dbstack;
inDataTip = ismember(‘datatipinfo’, {stack.name});
if ~usingTerminal || inDataTip
% print the message without color and return
fprintf(fmatString, varargin{:});
return;
end
bright = 1;
[colorName backColorName bright underline blink] = parseStyle(style);
colorCodes = getColorCode(colorName, bright);
backColorCodes = getBackColorCode(backColorName);
codes = [colorCodes; backColorCodes];
if underline
codes = [codes; 4];
end
if blink
codes = [codes; 5];
end
codeStr = strjoin(codes, ‘;’);
% evaluate the printf style message
contents = sprintf(fmatString, varargin{:});
% if the message ends with a newline, we should turn off
% formatting before the newline to avoid issues with
% background colors
if ~isempty(contents) && contents(end) == char(10)
contents = contents(1:end-1);
endOfLine = char(10);
else
endOfLine = ”;
end
str = [’33[‘ codeStr ‘m’ contents ’33[0m’ endOfLine];
fprintf(str);
end
function [colorName backColorName bright underline blink] = parseStyle(style)
defaultColor = ‘white’;
defaultBackColor = ‘onDefault’;
tokens = regexp(style, ‘(?<value>S+)[s]?’, ‘names’);
values = {tokens.value};
if ismember(‘bright’, values)
bright = true;
else
bright = false;
end
if ismember(‘underline’, values)
underline = true;
else
underline = false;
end
if ismember(‘blink’, values)
blink = true;
else
blink = false;
end
% find foreground color
colorList = {‘black’, ‘darkGray’, ‘lightGray’, ‘red’, ‘green’, ‘yellow’, …
‘blue’, ‘purple’, ‘cyan’, ‘lightGray’, ‘white’, ‘default’};
idxColor = find(ismember(colorList, values), 1);
if ~isempty(idxColor)
colorName = colorList{idxColor};
else
colorName = defaultColor;
end
% find background color
backColorList = {‘onBlack’, ‘onRed’, ‘onGreen’, ‘onYellow’, ‘onBlue’, …
‘onPurple’, ‘onCyan’, ‘onWhite’, ‘onDefault’};
idxBackColor = find(ismember(backColorList, values), 1);
if ~isempty(idxBackColor)
backColorName = backColorList{idxBackColor};
else
backColorName = defaultBackColor;
end
end
function colorCodes = getColorCode(colorName, bright)
switch colorName
case ‘black’
code = 30;
bright = 0;
case ‘darkGray’;
code = 30;
bright = 1;
case ‘red’
code = 31;
case ‘green’
code = 32;
case ‘yellow’
code = 33;
case ‘blue’
code = 34;
case ‘purple’
code = 35;
case ‘cyan’
code = 36;
case ‘lightGray’
code = 37;
bright = 0;
case ‘white’
code = 37;
bright = 1;
case ‘default’
code = 39;
end
if bright
colorCodes = [1; code];
else
colorCodes = [code];
end
end
function colorCodes = getBackColorCode(colorName)
switch colorName
case ‘onBlack’
code = 40;
case ‘onRed’
code = 41;
case ‘onGreen’
code = 42;
case ‘onYellow’
code = 43;
case ‘onBlue’
code = 44;
case ‘onPurple’
code = 45;
case ‘onCyan’
code = 46;
case ‘onWhite’
code = 47;
case ‘onDefault’
code = 49;
end
colorCodes = code;
end
function str = strjoin(strCell, join)
% str = strjoin(strCell, join)
% creates a string by concatenating the elements of strCell, separated by the string
% in join (default = ‘, ‘)
%
% e.g. strCell = {‘a’,’b’}, join = ‘, ‘ [ default ] –> str = ‘a, b’
if nargin < 2
join = ‘, ‘;
end
if isempty(strCell)
str = ”;
else
if isnumeric(strCell) || islogical(strCell)
% convert numeric vectors to strings
strCell = arrayfun(@num2str, strCell, ‘UniformOutput’, false);
end
str = cellfun(@(str) [str join], strCell, …
‘UniformOutput’, false);
str = [str{:}];
str = str(1:end-length(join));
end
endthis used to work in Matlab 2019b and before, to show a progressbar in parfor loop:
%% par pool
[~, output] = system(‘free -b | awk ”/Mem/{print $2}”’);
total_memory = str2double(output);
myCluster = min(ceil(total_memory / 1024^2 / 2 / 1000), round(maxNumCompThreads));
if isempty(gcp(‘nocreate’))
pool=parpool(myCluster,’IdleTimeout’, 604800);%1 week
end
nsim = 50
%% ———————————–
global P;
P = 1;
DataQueue = parallel.pool.DataQueue;
textprogressbar(‘start: ‘);
afterEach(DataQueue, @(ss) textprogressbar(P/nsim*100));
afterEach(DataQueue, @updateP);
parfor i = 1:nsim
send(DataQueue,i);
%someprocess
pause(0.1)
end
textprogressbar(‘ done’)
Now I updated to 2024a Update 4 (24.1.0.2628055). And even though the parloop run just fine, the progressbar is never updated.
Here the code of textprorgessbar I take somewhere from around here:
function textprogressbar(c)
% This function creates a text progress bar. It should be called with a
% STRING argument to initialize and terminate. Otherwise the number correspoding
% to progress in % should be supplied.
% INPUTS: C Either: Text string to initialize or terminate
% Percentage number to show progress
% OUTPUTS: N/A
% Example: Please refer to demo_textprogressbar.m
% Author: Paul Proteus (e-mail: proteus.paul (at) yahoo (dot) com)
% Version: 1.0
% Changes tracker: 29.06.2010 – First version
% Inspired by: http://blogs.mathworks.com/loren/2007/08/01/monitoring-progress-of-a-calculation/
%% Initialization
persistent strCR; % Carriage return pesistent variable
% Vizualization parameters
strPercentageLength = 6; % Length of percentage string (must be >5)
strDotsMaximum = 10; % The total number of dots in a progress bar
%% Main
if isempty(strCR) && ~ischar(c),
% Progress bar must be initialized with a string
error(‘The text progress must be initialized with a string’);
elseif isempty(strCR) && ischar(c),
% Progress bar – initialization
% fprintf(‘%s’,c);
tcprintf(‘green’,c);
strCR = -1;
elseif ~isempty(strCR) && ischar(c),
% Progress bar – termination
strCR = [];
% fprintf([c ‘n’]);
tcprintf(‘red’,[c ‘n’]);
elseif isnumeric(c)
% Progress bar – normal progress
c = floor(c);
percentageOut = [num2str(c) ‘%%’];
percentageOut = [percentageOut repmat(‘ ‘,1,strPercentageLength-length(percentageOut)-1)];
nDots = floor(c/100*strDotsMaximum);
dotOut = [‘[‘ repmat(‘.’,1,nDots) repmat(‘ ‘,1,strDotsMaximum-nDots) ‘]’];
strOut = [percentageOut dotOut];
% Print it on the screen BAR!!!!
if strCR == -1,
% Don’t do carriage return during first run
fprintf(strOut);
% tcprintf(‘yellow’,strOut);
else
% Do it during all the other runs
fprintf([strCR strOut]);
% tcprintf(‘yellow’,[strCR strOut]);
end
% Update carriage return
strCR = repmat(‘b’,1,length(strOut)-1);
else
% Any other unexpected input
error(‘Unsupported argument type’);
end
%%—————————————————
function tcprintf(style, fmatString, varargin)
% Uses ANSI escape codes to print colored output when using MATLAB
% from a terminal. If not running in a terminal, or if called by MATLAB’s
% datatipinfo function, tcprintf reverts to standard printf. The latter is
% desirable if tcprintf is used within an object’s disp() method to avoid
% seeing the ANSI characters here.
%
% The first argument is an style description that consists of space-separated
% words. These words may include:
%
% one of the following colors:
% black, red, green, yellow, blue, purple, cyan, darkGray, lightGray, white
%
% one of the following background colors:
% onBlack, onRed, onGreen, onYellow, onBlue, onPurple, onCyan, onWhite
%
% and any of the following modifiers:
% bright : use the bright (or bold) form of the color, not applicable for
% black, darkGray, lightGray, or white
% underline : draw an underline under each character
% blink : This is a mistake. Please don’t use this ever.
%
% Example:
% tcprintf(‘lightGray onRed underline’, ‘Message: %20sn’, msg);
%
% Author: Dan O’Shea dan at djoshea.com (c) 2012
%
% Released under the open source BSD license
% opensource.org/licenses/bsd-license.php
if nargin < 2 || ~ischar(style) || ~ischar(fmatString)
error(‘Usage: tcprintf(style, fmatString, …)’);
end
% determine if we’re using
usingTerminal = ~usejava(‘desktop’);
% determine if datatipinfo is higher on the stack. If tcprintf
% is used within an object’s disp() method, we don’t want to
% use color in the hover datatip or all you’ll see are ANSI codes.
stack = dbstack;
inDataTip = ismember(‘datatipinfo’, {stack.name});
if ~usingTerminal || inDataTip
% print the message without color and return
fprintf(fmatString, varargin{:});
return;
end
bright = 1;
[colorName backColorName bright underline blink] = parseStyle(style);
colorCodes = getColorCode(colorName, bright);
backColorCodes = getBackColorCode(backColorName);
codes = [colorCodes; backColorCodes];
if underline
codes = [codes; 4];
end
if blink
codes = [codes; 5];
end
codeStr = strjoin(codes, ‘;’);
% evaluate the printf style message
contents = sprintf(fmatString, varargin{:});
% if the message ends with a newline, we should turn off
% formatting before the newline to avoid issues with
% background colors
if ~isempty(contents) && contents(end) == char(10)
contents = contents(1:end-1);
endOfLine = char(10);
else
endOfLine = ”;
end
str = [’33[‘ codeStr ‘m’ contents ’33[0m’ endOfLine];
fprintf(str);
end
function [colorName backColorName bright underline blink] = parseStyle(style)
defaultColor = ‘white’;
defaultBackColor = ‘onDefault’;
tokens = regexp(style, ‘(?<value>S+)[s]?’, ‘names’);
values = {tokens.value};
if ismember(‘bright’, values)
bright = true;
else
bright = false;
end
if ismember(‘underline’, values)
underline = true;
else
underline = false;
end
if ismember(‘blink’, values)
blink = true;
else
blink = false;
end
% find foreground color
colorList = {‘black’, ‘darkGray’, ‘lightGray’, ‘red’, ‘green’, ‘yellow’, …
‘blue’, ‘purple’, ‘cyan’, ‘lightGray’, ‘white’, ‘default’};
idxColor = find(ismember(colorList, values), 1);
if ~isempty(idxColor)
colorName = colorList{idxColor};
else
colorName = defaultColor;
end
% find background color
backColorList = {‘onBlack’, ‘onRed’, ‘onGreen’, ‘onYellow’, ‘onBlue’, …
‘onPurple’, ‘onCyan’, ‘onWhite’, ‘onDefault’};
idxBackColor = find(ismember(backColorList, values), 1);
if ~isempty(idxBackColor)
backColorName = backColorList{idxBackColor};
else
backColorName = defaultBackColor;
end
end
function colorCodes = getColorCode(colorName, bright)
switch colorName
case ‘black’
code = 30;
bright = 0;
case ‘darkGray’;
code = 30;
bright = 1;
case ‘red’
code = 31;
case ‘green’
code = 32;
case ‘yellow’
code = 33;
case ‘blue’
code = 34;
case ‘purple’
code = 35;
case ‘cyan’
code = 36;
case ‘lightGray’
code = 37;
bright = 0;
case ‘white’
code = 37;
bright = 1;
case ‘default’
code = 39;
end
if bright
colorCodes = [1; code];
else
colorCodes = [code];
end
end
function colorCodes = getBackColorCode(colorName)
switch colorName
case ‘onBlack’
code = 40;
case ‘onRed’
code = 41;
case ‘onGreen’
code = 42;
case ‘onYellow’
code = 43;
case ‘onBlue’
code = 44;
case ‘onPurple’
code = 45;
case ‘onCyan’
code = 46;
case ‘onWhite’
code = 47;
case ‘onDefault’
code = 49;
end
colorCodes = code;
end
function str = strjoin(strCell, join)
% str = strjoin(strCell, join)
% creates a string by concatenating the elements of strCell, separated by the string
% in join (default = ‘, ‘)
%
% e.g. strCell = {‘a’,’b’}, join = ‘, ‘ [ default ] –> str = ‘a, b’
if nargin < 2
join = ‘, ‘;
end
if isempty(strCell)
str = ”;
else
if isnumeric(strCell) || islogical(strCell)
% convert numeric vectors to strings
strCell = arrayfun(@num2str, strCell, ‘UniformOutput’, false);
end
str = cellfun(@(str) [str join], strCell, …
‘UniformOutput’, false);
str = [str{:}];
str = str(1:end-length(join));
end
end this used to work in Matlab 2019b and before, to show a progressbar in parfor loop:
%% par pool
[~, output] = system(‘free -b | awk ”/Mem/{print $2}”’);
total_memory = str2double(output);
myCluster = min(ceil(total_memory / 1024^2 / 2 / 1000), round(maxNumCompThreads));
if isempty(gcp(‘nocreate’))
pool=parpool(myCluster,’IdleTimeout’, 604800);%1 week
end
nsim = 50
%% ———————————–
global P;
P = 1;
DataQueue = parallel.pool.DataQueue;
textprogressbar(‘start: ‘);
afterEach(DataQueue, @(ss) textprogressbar(P/nsim*100));
afterEach(DataQueue, @updateP);
parfor i = 1:nsim
send(DataQueue,i);
%someprocess
pause(0.1)
end
textprogressbar(‘ done’)
Now I updated to 2024a Update 4 (24.1.0.2628055). And even though the parloop run just fine, the progressbar is never updated.
Here the code of textprorgessbar I take somewhere from around here:
function textprogressbar(c)
% This function creates a text progress bar. It should be called with a
% STRING argument to initialize and terminate. Otherwise the number correspoding
% to progress in % should be supplied.
% INPUTS: C Either: Text string to initialize or terminate
% Percentage number to show progress
% OUTPUTS: N/A
% Example: Please refer to demo_textprogressbar.m
% Author: Paul Proteus (e-mail: proteus.paul (at) yahoo (dot) com)
% Version: 1.0
% Changes tracker: 29.06.2010 – First version
% Inspired by: http://blogs.mathworks.com/loren/2007/08/01/monitoring-progress-of-a-calculation/
%% Initialization
persistent strCR; % Carriage return pesistent variable
% Vizualization parameters
strPercentageLength = 6; % Length of percentage string (must be >5)
strDotsMaximum = 10; % The total number of dots in a progress bar
%% Main
if isempty(strCR) && ~ischar(c),
% Progress bar must be initialized with a string
error(‘The text progress must be initialized with a string’);
elseif isempty(strCR) && ischar(c),
% Progress bar – initialization
% fprintf(‘%s’,c);
tcprintf(‘green’,c);
strCR = -1;
elseif ~isempty(strCR) && ischar(c),
% Progress bar – termination
strCR = [];
% fprintf([c ‘n’]);
tcprintf(‘red’,[c ‘n’]);
elseif isnumeric(c)
% Progress bar – normal progress
c = floor(c);
percentageOut = [num2str(c) ‘%%’];
percentageOut = [percentageOut repmat(‘ ‘,1,strPercentageLength-length(percentageOut)-1)];
nDots = floor(c/100*strDotsMaximum);
dotOut = [‘[‘ repmat(‘.’,1,nDots) repmat(‘ ‘,1,strDotsMaximum-nDots) ‘]’];
strOut = [percentageOut dotOut];
% Print it on the screen BAR!!!!
if strCR == -1,
% Don’t do carriage return during first run
fprintf(strOut);
% tcprintf(‘yellow’,strOut);
else
% Do it during all the other runs
fprintf([strCR strOut]);
% tcprintf(‘yellow’,[strCR strOut]);
end
% Update carriage return
strCR = repmat(‘b’,1,length(strOut)-1);
else
% Any other unexpected input
error(‘Unsupported argument type’);
end
%%—————————————————
function tcprintf(style, fmatString, varargin)
% Uses ANSI escape codes to print colored output when using MATLAB
% from a terminal. If not running in a terminal, or if called by MATLAB’s
% datatipinfo function, tcprintf reverts to standard printf. The latter is
% desirable if tcprintf is used within an object’s disp() method to avoid
% seeing the ANSI characters here.
%
% The first argument is an style description that consists of space-separated
% words. These words may include:
%
% one of the following colors:
% black, red, green, yellow, blue, purple, cyan, darkGray, lightGray, white
%
% one of the following background colors:
% onBlack, onRed, onGreen, onYellow, onBlue, onPurple, onCyan, onWhite
%
% and any of the following modifiers:
% bright : use the bright (or bold) form of the color, not applicable for
% black, darkGray, lightGray, or white
% underline : draw an underline under each character
% blink : This is a mistake. Please don’t use this ever.
%
% Example:
% tcprintf(‘lightGray onRed underline’, ‘Message: %20sn’, msg);
%
% Author: Dan O’Shea dan at djoshea.com (c) 2012
%
% Released under the open source BSD license
% opensource.org/licenses/bsd-license.php
if nargin < 2 || ~ischar(style) || ~ischar(fmatString)
error(‘Usage: tcprintf(style, fmatString, …)’);
end
% determine if we’re using
usingTerminal = ~usejava(‘desktop’);
% determine if datatipinfo is higher on the stack. If tcprintf
% is used within an object’s disp() method, we don’t want to
% use color in the hover datatip or all you’ll see are ANSI codes.
stack = dbstack;
inDataTip = ismember(‘datatipinfo’, {stack.name});
if ~usingTerminal || inDataTip
% print the message without color and return
fprintf(fmatString, varargin{:});
return;
end
bright = 1;
[colorName backColorName bright underline blink] = parseStyle(style);
colorCodes = getColorCode(colorName, bright);
backColorCodes = getBackColorCode(backColorName);
codes = [colorCodes; backColorCodes];
if underline
codes = [codes; 4];
end
if blink
codes = [codes; 5];
end
codeStr = strjoin(codes, ‘;’);
% evaluate the printf style message
contents = sprintf(fmatString, varargin{:});
% if the message ends with a newline, we should turn off
% formatting before the newline to avoid issues with
% background colors
if ~isempty(contents) && contents(end) == char(10)
contents = contents(1:end-1);
endOfLine = char(10);
else
endOfLine = ”;
end
str = [’33[‘ codeStr ‘m’ contents ’33[0m’ endOfLine];
fprintf(str);
end
function [colorName backColorName bright underline blink] = parseStyle(style)
defaultColor = ‘white’;
defaultBackColor = ‘onDefault’;
tokens = regexp(style, ‘(?<value>S+)[s]?’, ‘names’);
values = {tokens.value};
if ismember(‘bright’, values)
bright = true;
else
bright = false;
end
if ismember(‘underline’, values)
underline = true;
else
underline = false;
end
if ismember(‘blink’, values)
blink = true;
else
blink = false;
end
% find foreground color
colorList = {‘black’, ‘darkGray’, ‘lightGray’, ‘red’, ‘green’, ‘yellow’, …
‘blue’, ‘purple’, ‘cyan’, ‘lightGray’, ‘white’, ‘default’};
idxColor = find(ismember(colorList, values), 1);
if ~isempty(idxColor)
colorName = colorList{idxColor};
else
colorName = defaultColor;
end
% find background color
backColorList = {‘onBlack’, ‘onRed’, ‘onGreen’, ‘onYellow’, ‘onBlue’, …
‘onPurple’, ‘onCyan’, ‘onWhite’, ‘onDefault’};
idxBackColor = find(ismember(backColorList, values), 1);
if ~isempty(idxBackColor)
backColorName = backColorList{idxBackColor};
else
backColorName = defaultBackColor;
end
end
function colorCodes = getColorCode(colorName, bright)
switch colorName
case ‘black’
code = 30;
bright = 0;
case ‘darkGray’;
code = 30;
bright = 1;
case ‘red’
code = 31;
case ‘green’
code = 32;
case ‘yellow’
code = 33;
case ‘blue’
code = 34;
case ‘purple’
code = 35;
case ‘cyan’
code = 36;
case ‘lightGray’
code = 37;
bright = 0;
case ‘white’
code = 37;
bright = 1;
case ‘default’
code = 39;
end
if bright
colorCodes = [1; code];
else
colorCodes = [code];
end
end
function colorCodes = getBackColorCode(colorName)
switch colorName
case ‘onBlack’
code = 40;
case ‘onRed’
code = 41;
case ‘onGreen’
code = 42;
case ‘onYellow’
code = 43;
case ‘onBlue’
code = 44;
case ‘onPurple’
code = 45;
case ‘onCyan’
code = 46;
case ‘onWhite’
code = 47;
case ‘onDefault’
code = 49;
end
colorCodes = code;
end
function str = strjoin(strCell, join)
% str = strjoin(strCell, join)
% creates a string by concatenating the elements of strCell, separated by the string
% in join (default = ‘, ‘)
%
% e.g. strCell = {‘a’,’b’}, join = ‘, ‘ [ default ] –> str = ‘a, b’
if nargin < 2
join = ‘, ‘;
end
if isempty(strCell)
str = ”;
else
if isnumeric(strCell) || islogical(strCell)
% convert numeric vectors to strings
strCell = arrayfun(@num2str, strCell, ‘UniformOutput’, false);
end
str = cellfun(@(str) [str join], strCell, …
‘UniformOutput’, false);
str = [str{:}];
str = str(1:end-length(join));
end
end parfor, textprogressbar, 2024a MATLAB Answers — New Questions
Prevent error: “Unable to communicate with required MathWorks services (error 5001)”
I am encountering the error described in https://es.mathworks.com/matlabcentral/answers/1814080-why-do-i-receive-error-5001-unable-to-access-services-required-to-run-matlab#answer_1062795.
In my opinion this is not a good resolution. It is a very annoying error that is NOT properly addressed. In my case, I am running neuroimaging pipelines constantly and this bug continually breaks my runs. Is there any way to prevent this error from suddenly popping up that doesn’t involve having to kill processes? Ideally I would like to prevent it.
Im running R2024a.I am encountering the error described in https://es.mathworks.com/matlabcentral/answers/1814080-why-do-i-receive-error-5001-unable-to-access-services-required-to-run-matlab#answer_1062795.
In my opinion this is not a good resolution. It is a very annoying error that is NOT properly addressed. In my case, I am running neuroimaging pipelines constantly and this bug continually breaks my runs. Is there any way to prevent this error from suddenly popping up that doesn’t involve having to kill processes? Ideally I would like to prevent it.
Im running R2024a. I am encountering the error described in https://es.mathworks.com/matlabcentral/answers/1814080-why-do-i-receive-error-5001-unable-to-access-services-required-to-run-matlab#answer_1062795.
In my opinion this is not a good resolution. It is a very annoying error that is NOT properly addressed. In my case, I am running neuroimaging pipelines constantly and this bug continually breaks my runs. Is there any way to prevent this error from suddenly popping up that doesn’t involve having to kill processes? Ideally I would like to prevent it.
Im running R2024a. error 5001 MATLAB Answers — New Questions
ARIMA in Econometric Modeler
Hi,
I apologize for the simple question, but I’m very new to econometric analysis in MATLAB and not so experienced in Stata. Essentially, I have a database (attached Excel file) that I’m using to estimate an ARIMA(1,1,4) model for the variable "wpi". I’ve followed standard procedures in both Stata and MATLAB based on educational videos, but I’m receiving different coefficient estimates. I’ve made sure that both Stata and MATLAB use the first difference in the dependent variable, but I’m unsure what I’m doing wrong to get different estimates.
In fact, Stata Corp has a video on this exercise (https://www.youtube.com/watch?v=8xt4q7KHfBs), where the author [mistakenly used "wpi" instead of "log(wpi)"] and reports the results at minute 7:26. You can see the coefficient values there. When I fit the exact same model in MATLAB Econometric Modeller, my coefficient estimates are different. For example, the MATLAB constant estimate is 0.15, whereas in Stata it’s 0.74, and so on.
Could you please help me diagnose the problem? I’m attaching the dataset here. Thank you very much.Hi,
I apologize for the simple question, but I’m very new to econometric analysis in MATLAB and not so experienced in Stata. Essentially, I have a database (attached Excel file) that I’m using to estimate an ARIMA(1,1,4) model for the variable "wpi". I’ve followed standard procedures in both Stata and MATLAB based on educational videos, but I’m receiving different coefficient estimates. I’ve made sure that both Stata and MATLAB use the first difference in the dependent variable, but I’m unsure what I’m doing wrong to get different estimates.
In fact, Stata Corp has a video on this exercise (https://www.youtube.com/watch?v=8xt4q7KHfBs), where the author [mistakenly used "wpi" instead of "log(wpi)"] and reports the results at minute 7:26. You can see the coefficient values there. When I fit the exact same model in MATLAB Econometric Modeller, my coefficient estimates are different. For example, the MATLAB constant estimate is 0.15, whereas in Stata it’s 0.74, and so on.
Could you please help me diagnose the problem? I’m attaching the dataset here. Thank you very much. Hi,
I apologize for the simple question, but I’m very new to econometric analysis in MATLAB and not so experienced in Stata. Essentially, I have a database (attached Excel file) that I’m using to estimate an ARIMA(1,1,4) model for the variable "wpi". I’ve followed standard procedures in both Stata and MATLAB based on educational videos, but I’m receiving different coefficient estimates. I’ve made sure that both Stata and MATLAB use the first difference in the dependent variable, but I’m unsure what I’m doing wrong to get different estimates.
In fact, Stata Corp has a video on this exercise (https://www.youtube.com/watch?v=8xt4q7KHfBs), where the author [mistakenly used "wpi" instead of "log(wpi)"] and reports the results at minute 7:26. You can see the coefficient values there. When I fit the exact same model in MATLAB Econometric Modeller, my coefficient estimates are different. For example, the MATLAB constant estimate is 0.15, whereas in Stata it’s 0.74, and so on.
Could you please help me diagnose the problem? I’m attaching the dataset here. Thank you very much. econometric modeler, arima, stata MATLAB Answers — New Questions