Tag Archives: matlab
Can I communicate through Modbus protocol from MATLAB/Simulink?
I want to know if MathWorks offers any products that I can use to communicate through Modbus® protocol.I want to know if MathWorks offers any products that I can use to communicate through Modbus® protocol. I want to know if MathWorks offers any products that I can use to communicate through Modbus® protocol. MATLAB Answers — New Questions
How to speed up vectorized operations for dynamic programming
I would like to speed up the following code which solves a discrete dynamic programming problem using the method of successive approximations, as described e.g. in Bertsekas.
The algorithm is made of two steps. In step 1, I precompute the payoff array R(a’,a,z) where a’ is the action and (a,z) are the states. In step 2 I compute the value function using the method of successive approximations: I guess V0, then I compute an updated V1 and finally I check if ||V1-V0|| is less than a tolerance level. If it is, I stop, otherwise I set V0=V1 and go on.
I profiled the code (see below a MWE) and the two most time-consuming lines are the following ones:
(1) RHS = Ret+beta*permute(EV,[1,3,2]);
(2) [max_val,max_ind] = max(RHS,[],1);
Line (1) takes up 63% of the total running time, line (2) takes 32%. As you can see I have already vectorized all loops.
I would be very grateful for any suggestion. I post below a MWE.
%% Solve income fluctuation problem CPU
clear;clc;close all
%% Economic parameters
sigma = 2;
r = 0.03;
beta = 0.96;
PZ = [0.60 0.40;
0.05 0.95];
z_grid = [0.5 1.0]’;
n_z = length(z_grid);
b = 0; %lower bound for asset holdings a
grid_max = 4;
n_a = 500; % IN PRACTICE THIS IS EQUAL TO 5000-10000
R = 1+r;
a_grid = linspace(-b,grid_max,n_a)’;
if sigma==1
fun_u = @(c) log(c);
else
fun_u = @(c) c.^(1-sigma)/(1-sigma);
end
%% Computational parameters
verbose = 0;
tiny = 1e-8; %very small positive number
tol = 1e-6; %tolerance for VFI and TI
max_iter = 500; %maximum num. of iterations for both VFI and TI
%% Start timing
tic
%% STEP 1- Precompute current payoff array R(a’,a,z)
a_tomorrow = a_grid; %(a’,1,1)
a_today = a_grid’; %(1,a,1)
z_today = shiftdim(z_grid,-2); %(1,1,z)
cons = (1+r)*a_today+z_today-a_tomorrow;
Ret = fun_u(cons); %size: [n_a,n_a,n_z]
Ret(cons<=0) = -inf;
%% STEP 2 – Value function iteration
iter = 1;
err = tol+1;
V0 = zeros(n_a,n_z);
while err>tol && iter<=max_iter
EV = V0*PZ’; %(a’,z)
RHS = Ret+beta*permute(EV,[1,3,2]);
[max_val,max_ind] = max(RHS,[],1);
V1 = squeeze(max_val);
pol_ind_ap = squeeze(max_ind);
err = max(abs(V0(:)-V1(:)));
if verbose==1
fprintf(‘iter = %d, err = %f n’,iter,err)
end
iter = iter+1;
V0 = V1;
end
if err>tol
error(‘VFI did not converge!’)
else
fprintf(‘VFI converged after = %d iterations n’,iter)
end
pol_ap = a_grid(pol_ind_ap);
pol_c = (1+r)*a_grid+z_grid’-pol_ap;
%% End timing
toc
%% Figures
figure
plot(a_grid,pol_c(:,1),’linewidth’,2)
hold on
plot(a_grid,pol_c(:,2),’linewidth’,2)
legend(‘Low shock’,’High shock’,’Location’,’NorthWest’)
xlabel(‘asset level’)
ylabel(‘consumption’)
title(‘Consumption Policy Function’)
figure
plot(a_grid,a_grid,’–‘,’linewidth’,2)
hold on
plot(a_grid,pol_ap(:,1),’linewidth’,2)
hold on
plot(a_grid,pol_ap(:,2),’linewidth’,2)
legend(’45 line’,’Low shock’,’High shock’,’Location’,’NorthWest’)
xlabel(‘Current period assets’)
ylabel(‘Next-period assets’)
title(‘Assets Policy Function’)I would like to speed up the following code which solves a discrete dynamic programming problem using the method of successive approximations, as described e.g. in Bertsekas.
The algorithm is made of two steps. In step 1, I precompute the payoff array R(a’,a,z) where a’ is the action and (a,z) are the states. In step 2 I compute the value function using the method of successive approximations: I guess V0, then I compute an updated V1 and finally I check if ||V1-V0|| is less than a tolerance level. If it is, I stop, otherwise I set V0=V1 and go on.
I profiled the code (see below a MWE) and the two most time-consuming lines are the following ones:
(1) RHS = Ret+beta*permute(EV,[1,3,2]);
(2) [max_val,max_ind] = max(RHS,[],1);
Line (1) takes up 63% of the total running time, line (2) takes 32%. As you can see I have already vectorized all loops.
I would be very grateful for any suggestion. I post below a MWE.
%% Solve income fluctuation problem CPU
clear;clc;close all
%% Economic parameters
sigma = 2;
r = 0.03;
beta = 0.96;
PZ = [0.60 0.40;
0.05 0.95];
z_grid = [0.5 1.0]’;
n_z = length(z_grid);
b = 0; %lower bound for asset holdings a
grid_max = 4;
n_a = 500; % IN PRACTICE THIS IS EQUAL TO 5000-10000
R = 1+r;
a_grid = linspace(-b,grid_max,n_a)’;
if sigma==1
fun_u = @(c) log(c);
else
fun_u = @(c) c.^(1-sigma)/(1-sigma);
end
%% Computational parameters
verbose = 0;
tiny = 1e-8; %very small positive number
tol = 1e-6; %tolerance for VFI and TI
max_iter = 500; %maximum num. of iterations for both VFI and TI
%% Start timing
tic
%% STEP 1- Precompute current payoff array R(a’,a,z)
a_tomorrow = a_grid; %(a’,1,1)
a_today = a_grid’; %(1,a,1)
z_today = shiftdim(z_grid,-2); %(1,1,z)
cons = (1+r)*a_today+z_today-a_tomorrow;
Ret = fun_u(cons); %size: [n_a,n_a,n_z]
Ret(cons<=0) = -inf;
%% STEP 2 – Value function iteration
iter = 1;
err = tol+1;
V0 = zeros(n_a,n_z);
while err>tol && iter<=max_iter
EV = V0*PZ’; %(a’,z)
RHS = Ret+beta*permute(EV,[1,3,2]);
[max_val,max_ind] = max(RHS,[],1);
V1 = squeeze(max_val);
pol_ind_ap = squeeze(max_ind);
err = max(abs(V0(:)-V1(:)));
if verbose==1
fprintf(‘iter = %d, err = %f n’,iter,err)
end
iter = iter+1;
V0 = V1;
end
if err>tol
error(‘VFI did not converge!’)
else
fprintf(‘VFI converged after = %d iterations n’,iter)
end
pol_ap = a_grid(pol_ind_ap);
pol_c = (1+r)*a_grid+z_grid’-pol_ap;
%% End timing
toc
%% Figures
figure
plot(a_grid,pol_c(:,1),’linewidth’,2)
hold on
plot(a_grid,pol_c(:,2),’linewidth’,2)
legend(‘Low shock’,’High shock’,’Location’,’NorthWest’)
xlabel(‘asset level’)
ylabel(‘consumption’)
title(‘Consumption Policy Function’)
figure
plot(a_grid,a_grid,’–‘,’linewidth’,2)
hold on
plot(a_grid,pol_ap(:,1),’linewidth’,2)
hold on
plot(a_grid,pol_ap(:,2),’linewidth’,2)
legend(’45 line’,’Low shock’,’High shock’,’Location’,’NorthWest’)
xlabel(‘Current period assets’)
ylabel(‘Next-period assets’)
title(‘Assets Policy Function’) I would like to speed up the following code which solves a discrete dynamic programming problem using the method of successive approximations, as described e.g. in Bertsekas.
The algorithm is made of two steps. In step 1, I precompute the payoff array R(a’,a,z) where a’ is the action and (a,z) are the states. In step 2 I compute the value function using the method of successive approximations: I guess V0, then I compute an updated V1 and finally I check if ||V1-V0|| is less than a tolerance level. If it is, I stop, otherwise I set V0=V1 and go on.
I profiled the code (see below a MWE) and the two most time-consuming lines are the following ones:
(1) RHS = Ret+beta*permute(EV,[1,3,2]);
(2) [max_val,max_ind] = max(RHS,[],1);
Line (1) takes up 63% of the total running time, line (2) takes 32%. As you can see I have already vectorized all loops.
I would be very grateful for any suggestion. I post below a MWE.
%% Solve income fluctuation problem CPU
clear;clc;close all
%% Economic parameters
sigma = 2;
r = 0.03;
beta = 0.96;
PZ = [0.60 0.40;
0.05 0.95];
z_grid = [0.5 1.0]’;
n_z = length(z_grid);
b = 0; %lower bound for asset holdings a
grid_max = 4;
n_a = 500; % IN PRACTICE THIS IS EQUAL TO 5000-10000
R = 1+r;
a_grid = linspace(-b,grid_max,n_a)’;
if sigma==1
fun_u = @(c) log(c);
else
fun_u = @(c) c.^(1-sigma)/(1-sigma);
end
%% Computational parameters
verbose = 0;
tiny = 1e-8; %very small positive number
tol = 1e-6; %tolerance for VFI and TI
max_iter = 500; %maximum num. of iterations for both VFI and TI
%% Start timing
tic
%% STEP 1- Precompute current payoff array R(a’,a,z)
a_tomorrow = a_grid; %(a’,1,1)
a_today = a_grid’; %(1,a,1)
z_today = shiftdim(z_grid,-2); %(1,1,z)
cons = (1+r)*a_today+z_today-a_tomorrow;
Ret = fun_u(cons); %size: [n_a,n_a,n_z]
Ret(cons<=0) = -inf;
%% STEP 2 – Value function iteration
iter = 1;
err = tol+1;
V0 = zeros(n_a,n_z);
while err>tol && iter<=max_iter
EV = V0*PZ’; %(a’,z)
RHS = Ret+beta*permute(EV,[1,3,2]);
[max_val,max_ind] = max(RHS,[],1);
V1 = squeeze(max_val);
pol_ind_ap = squeeze(max_ind);
err = max(abs(V0(:)-V1(:)));
if verbose==1
fprintf(‘iter = %d, err = %f n’,iter,err)
end
iter = iter+1;
V0 = V1;
end
if err>tol
error(‘VFI did not converge!’)
else
fprintf(‘VFI converged after = %d iterations n’,iter)
end
pol_ap = a_grid(pol_ind_ap);
pol_c = (1+r)*a_grid+z_grid’-pol_ap;
%% End timing
toc
%% Figures
figure
plot(a_grid,pol_c(:,1),’linewidth’,2)
hold on
plot(a_grid,pol_c(:,2),’linewidth’,2)
legend(‘Low shock’,’High shock’,’Location’,’NorthWest’)
xlabel(‘asset level’)
ylabel(‘consumption’)
title(‘Consumption Policy Function’)
figure
plot(a_grid,a_grid,’–‘,’linewidth’,2)
hold on
plot(a_grid,pol_ap(:,1),’linewidth’,2)
hold on
plot(a_grid,pol_ap(:,2),’linewidth’,2)
legend(’45 line’,’Low shock’,’High shock’,’Location’,’NorthWest’)
xlabel(‘Current period assets’)
ylabel(‘Next-period assets’)
title(‘Assets Policy Function’) vectorized, performance MATLAB Answers — New Questions
Zero forcing equalization plotting
Hello, I am working on this matlab script for my final paper and simulating the transmission of 1 pulse. First it gets shaped as a Raised Cossine pulse with a filter, then the transmitted Tx signal goes through a low-pass butterworth filter that acts like a channel introducing distortion to the pulse, then the received Rx signal comes to a Zero Forcing Equalizer filter that should correct the low-pass filter distortion.
The problem I’m facing is when I try to plot the pulse, here’s the code:
clear;clf;clc;close all;
% This script performs a transmission of 1 pulse shaped with Raised Cossine
% that receives a distortion from a butterworth low-pass filter then
% the pulse gets an equalization from a Zero Forcing filter
% Building RC pulse shaping filter
rf = 0.5; % Roll-off factor
span = 16; % Pulse truncation factor
sps = 10; % Samples per pulse
p_rc = rcosdesign(rf,span,sps,"normal"); % Designing filter
p_rc_norm = p_rc/max(p_rc); % Normalizing
h_span = span/2; % Half symbol span
% Setting Data parameters
L = 1; % Total Data pulses
Rb = 1000; % Data rate in bps
% For Rb = 1000, that means that symbol time -> Tb = 1 milisecond
Fs = Rb * sps; % Sampling frequency
x = 1; % Data signal
% Note: Not starting at zero because of filter group delay
tx = 1000*(h_span:h_span)/Rb; % x Time vector sampled
% at symbol rate in milliseconds -> Data
% Applying RC filter
x_rc = upfirdn(x, p_rc_norm, sps); % Upsampling with upfirdn
% Note: By applying filtering, remember that the peak response of the
% filter gets delayed by the group delay of the filter, so we need to
% get rid of transients so that the pulses can be overlapping when plotting
trans_1 = sps*h_span; % Number of points for transient before peak operation
trans_2 = sps*(h_span-1); % Number of points for transient after peak operation
tx_rc = 1000*(0:L*sps+trans_1+trans_2)/Fs; % x_rc Time vector sampled at
% sampling frequency in milliseconds -> Tx signal
% Building and applying channel distortion via butterworth low-pass filter
Wn_butter = 0.1; % Normalized cutoff frequency
n_butter = 4; % Butterworth nth-order
[b_chan,a_chan] = butter(n_butter, Wn_butter); % Low-pass filter coefficients
x_rc_ch = filtfilt(b_chan,a_chan,x_rc); % Used filtfilt() so that it doesn’t
% get any group delay when filtering
% Setting Zero Forcing Equalizer filter parameters
N2_plus_1 = 9; % Choose ZF EQ Filter Order = 2N+1 % Note: Odd number only
N2 = N2_plus_1 – 1;
% If ZF EQ Filter Order = 5, that means that N = 2, that also
% means that the matrix would be 5×5, because the row and column
% should be from Pr[0] to Pr[2N] = Pr[4] and from Pr[0] to Pr[-2N]= Pr[-4]
% Building and applying ZFE filter
zf_kTb_peak = max(x_rc_ch); % Identify pulse peak
zf_kTb_peak_pos = find(x_rc_ch==zf_kTb_peak); % Identify pulse peak position
Pr_minus_N2 = zf_kTb_peak_pos-(sps*N2); % Range points to feed the ZF equalizer: Pr[0] to Pr[-2N]
Pr_plus_N2 = zf_kTb_peak_pos+(sps*N2); % Range points to feed the ZF equalizer: Pr[0] to Pr[2N]
zf_kTb = x_rc_ch(Pr_minus_N2:sps:Pr_plus_N2); % Scrolling Rx signal
% to get kTb points (integer multiples"k" of symbol time"Tb")
zf_kTb = zf_kTb’;
zf_Pr_row = zf_kTb(1:round(length(zf_kTb)/2));
zf_Pr_row = zf_Pr_row(end:-1:1); % Getting Pr[0] to Pr[-2N] vector
zf_Pr_col = zf_kTb(round(length(zf_kTb)/2):end); % Getting Pr[0] to Pr[2N] vector
Pr = toeplitz(zf_Pr_col, zf_Pr_row); % With kTb points we can build Toeplitz Matrix
Po = zeros(round(length(zf_kTb)/2), 1); % Creating Po vector to force neighbour pulses to 0
Po(round(length(Po)/2)) = 1;
Ck_zf = inv(Pr)*Po; % Calculating ZFE filter coefficients
% Applying ZFE filter to Rx kTb points:
zf_kTb_ZFE = conv(zf_kTb, Ck_zf, ‘same’);
% Plot 1
figure(1)
stem(zf_kTb, ‘color’, [0.8500 0.3250 0.0980]);
hold on
stem(zf_kTb_ZFE, ‘color’, [0.9290 0.6940 0.1250]);
hold off;
xlabel(‘Symbol spaced points (kTb)’); ylabel(‘Magnitude’);
legend(‘Rx points’,’ZFE points’,’Location’,’southeast’);
% Applying ZFE filter to Rx signal
x_rc_ch_zf = conv(x_rc_ch, Ck_zf, ‘same’);
% Plot 2
figure(2)
stem(tx, x, ‘k’);
hold on;
plot(tx_rc, x_rc, ‘color’, [0 0.4470 0.7410]);
plot(tx_rc, x_rc_ch, ‘color’, [0.8500 0.3250 0.0980]);
plot(tx_rc, x_rc_ch_zf, ‘color’, [0.9290 0.6940 0.1250]);
hold off;
xlabel(‘Time (ms)’); ylabel(‘Magnitude’);
legend(‘Data’,’Tx Signal’,’Rx Signal’,’ZFE Signal’,’Location’,’southeast’);
For the first figure, the equalyzer is working like it should, it is forcing the symbol spaced points(kTb) to zero.
But for the second figure, when the whole discretized pulse from the Rx signal goes through the same ZFE filter, it doesn’t get equalyzed back to something like the Tx signal, it just gets a little bit bigger on the peak.
So my doubt is, can we equalyze the Rx pulse with this type of equalization and plot the equalized pulse to something close to Tx signal ?Or does it just works for the points of symbol time ?Hello, I am working on this matlab script for my final paper and simulating the transmission of 1 pulse. First it gets shaped as a Raised Cossine pulse with a filter, then the transmitted Tx signal goes through a low-pass butterworth filter that acts like a channel introducing distortion to the pulse, then the received Rx signal comes to a Zero Forcing Equalizer filter that should correct the low-pass filter distortion.
The problem I’m facing is when I try to plot the pulse, here’s the code:
clear;clf;clc;close all;
% This script performs a transmission of 1 pulse shaped with Raised Cossine
% that receives a distortion from a butterworth low-pass filter then
% the pulse gets an equalization from a Zero Forcing filter
% Building RC pulse shaping filter
rf = 0.5; % Roll-off factor
span = 16; % Pulse truncation factor
sps = 10; % Samples per pulse
p_rc = rcosdesign(rf,span,sps,"normal"); % Designing filter
p_rc_norm = p_rc/max(p_rc); % Normalizing
h_span = span/2; % Half symbol span
% Setting Data parameters
L = 1; % Total Data pulses
Rb = 1000; % Data rate in bps
% For Rb = 1000, that means that symbol time -> Tb = 1 milisecond
Fs = Rb * sps; % Sampling frequency
x = 1; % Data signal
% Note: Not starting at zero because of filter group delay
tx = 1000*(h_span:h_span)/Rb; % x Time vector sampled
% at symbol rate in milliseconds -> Data
% Applying RC filter
x_rc = upfirdn(x, p_rc_norm, sps); % Upsampling with upfirdn
% Note: By applying filtering, remember that the peak response of the
% filter gets delayed by the group delay of the filter, so we need to
% get rid of transients so that the pulses can be overlapping when plotting
trans_1 = sps*h_span; % Number of points for transient before peak operation
trans_2 = sps*(h_span-1); % Number of points for transient after peak operation
tx_rc = 1000*(0:L*sps+trans_1+trans_2)/Fs; % x_rc Time vector sampled at
% sampling frequency in milliseconds -> Tx signal
% Building and applying channel distortion via butterworth low-pass filter
Wn_butter = 0.1; % Normalized cutoff frequency
n_butter = 4; % Butterworth nth-order
[b_chan,a_chan] = butter(n_butter, Wn_butter); % Low-pass filter coefficients
x_rc_ch = filtfilt(b_chan,a_chan,x_rc); % Used filtfilt() so that it doesn’t
% get any group delay when filtering
% Setting Zero Forcing Equalizer filter parameters
N2_plus_1 = 9; % Choose ZF EQ Filter Order = 2N+1 % Note: Odd number only
N2 = N2_plus_1 – 1;
% If ZF EQ Filter Order = 5, that means that N = 2, that also
% means that the matrix would be 5×5, because the row and column
% should be from Pr[0] to Pr[2N] = Pr[4] and from Pr[0] to Pr[-2N]= Pr[-4]
% Building and applying ZFE filter
zf_kTb_peak = max(x_rc_ch); % Identify pulse peak
zf_kTb_peak_pos = find(x_rc_ch==zf_kTb_peak); % Identify pulse peak position
Pr_minus_N2 = zf_kTb_peak_pos-(sps*N2); % Range points to feed the ZF equalizer: Pr[0] to Pr[-2N]
Pr_plus_N2 = zf_kTb_peak_pos+(sps*N2); % Range points to feed the ZF equalizer: Pr[0] to Pr[2N]
zf_kTb = x_rc_ch(Pr_minus_N2:sps:Pr_plus_N2); % Scrolling Rx signal
% to get kTb points (integer multiples"k" of symbol time"Tb")
zf_kTb = zf_kTb’;
zf_Pr_row = zf_kTb(1:round(length(zf_kTb)/2));
zf_Pr_row = zf_Pr_row(end:-1:1); % Getting Pr[0] to Pr[-2N] vector
zf_Pr_col = zf_kTb(round(length(zf_kTb)/2):end); % Getting Pr[0] to Pr[2N] vector
Pr = toeplitz(zf_Pr_col, zf_Pr_row); % With kTb points we can build Toeplitz Matrix
Po = zeros(round(length(zf_kTb)/2), 1); % Creating Po vector to force neighbour pulses to 0
Po(round(length(Po)/2)) = 1;
Ck_zf = inv(Pr)*Po; % Calculating ZFE filter coefficients
% Applying ZFE filter to Rx kTb points:
zf_kTb_ZFE = conv(zf_kTb, Ck_zf, ‘same’);
% Plot 1
figure(1)
stem(zf_kTb, ‘color’, [0.8500 0.3250 0.0980]);
hold on
stem(zf_kTb_ZFE, ‘color’, [0.9290 0.6940 0.1250]);
hold off;
xlabel(‘Symbol spaced points (kTb)’); ylabel(‘Magnitude’);
legend(‘Rx points’,’ZFE points’,’Location’,’southeast’);
% Applying ZFE filter to Rx signal
x_rc_ch_zf = conv(x_rc_ch, Ck_zf, ‘same’);
% Plot 2
figure(2)
stem(tx, x, ‘k’);
hold on;
plot(tx_rc, x_rc, ‘color’, [0 0.4470 0.7410]);
plot(tx_rc, x_rc_ch, ‘color’, [0.8500 0.3250 0.0980]);
plot(tx_rc, x_rc_ch_zf, ‘color’, [0.9290 0.6940 0.1250]);
hold off;
xlabel(‘Time (ms)’); ylabel(‘Magnitude’);
legend(‘Data’,’Tx Signal’,’Rx Signal’,’ZFE Signal’,’Location’,’southeast’);
For the first figure, the equalyzer is working like it should, it is forcing the symbol spaced points(kTb) to zero.
But for the second figure, when the whole discretized pulse from the Rx signal goes through the same ZFE filter, it doesn’t get equalyzed back to something like the Tx signal, it just gets a little bit bigger on the peak.
So my doubt is, can we equalyze the Rx pulse with this type of equalization and plot the equalized pulse to something close to Tx signal ?Or does it just works for the points of symbol time ? Hello, I am working on this matlab script for my final paper and simulating the transmission of 1 pulse. First it gets shaped as a Raised Cossine pulse with a filter, then the transmitted Tx signal goes through a low-pass butterworth filter that acts like a channel introducing distortion to the pulse, then the received Rx signal comes to a Zero Forcing Equalizer filter that should correct the low-pass filter distortion.
The problem I’m facing is when I try to plot the pulse, here’s the code:
clear;clf;clc;close all;
% This script performs a transmission of 1 pulse shaped with Raised Cossine
% that receives a distortion from a butterworth low-pass filter then
% the pulse gets an equalization from a Zero Forcing filter
% Building RC pulse shaping filter
rf = 0.5; % Roll-off factor
span = 16; % Pulse truncation factor
sps = 10; % Samples per pulse
p_rc = rcosdesign(rf,span,sps,"normal"); % Designing filter
p_rc_norm = p_rc/max(p_rc); % Normalizing
h_span = span/2; % Half symbol span
% Setting Data parameters
L = 1; % Total Data pulses
Rb = 1000; % Data rate in bps
% For Rb = 1000, that means that symbol time -> Tb = 1 milisecond
Fs = Rb * sps; % Sampling frequency
x = 1; % Data signal
% Note: Not starting at zero because of filter group delay
tx = 1000*(h_span:h_span)/Rb; % x Time vector sampled
% at symbol rate in milliseconds -> Data
% Applying RC filter
x_rc = upfirdn(x, p_rc_norm, sps); % Upsampling with upfirdn
% Note: By applying filtering, remember that the peak response of the
% filter gets delayed by the group delay of the filter, so we need to
% get rid of transients so that the pulses can be overlapping when plotting
trans_1 = sps*h_span; % Number of points for transient before peak operation
trans_2 = sps*(h_span-1); % Number of points for transient after peak operation
tx_rc = 1000*(0:L*sps+trans_1+trans_2)/Fs; % x_rc Time vector sampled at
% sampling frequency in milliseconds -> Tx signal
% Building and applying channel distortion via butterworth low-pass filter
Wn_butter = 0.1; % Normalized cutoff frequency
n_butter = 4; % Butterworth nth-order
[b_chan,a_chan] = butter(n_butter, Wn_butter); % Low-pass filter coefficients
x_rc_ch = filtfilt(b_chan,a_chan,x_rc); % Used filtfilt() so that it doesn’t
% get any group delay when filtering
% Setting Zero Forcing Equalizer filter parameters
N2_plus_1 = 9; % Choose ZF EQ Filter Order = 2N+1 % Note: Odd number only
N2 = N2_plus_1 – 1;
% If ZF EQ Filter Order = 5, that means that N = 2, that also
% means that the matrix would be 5×5, because the row and column
% should be from Pr[0] to Pr[2N] = Pr[4] and from Pr[0] to Pr[-2N]= Pr[-4]
% Building and applying ZFE filter
zf_kTb_peak = max(x_rc_ch); % Identify pulse peak
zf_kTb_peak_pos = find(x_rc_ch==zf_kTb_peak); % Identify pulse peak position
Pr_minus_N2 = zf_kTb_peak_pos-(sps*N2); % Range points to feed the ZF equalizer: Pr[0] to Pr[-2N]
Pr_plus_N2 = zf_kTb_peak_pos+(sps*N2); % Range points to feed the ZF equalizer: Pr[0] to Pr[2N]
zf_kTb = x_rc_ch(Pr_minus_N2:sps:Pr_plus_N2); % Scrolling Rx signal
% to get kTb points (integer multiples"k" of symbol time"Tb")
zf_kTb = zf_kTb’;
zf_Pr_row = zf_kTb(1:round(length(zf_kTb)/2));
zf_Pr_row = zf_Pr_row(end:-1:1); % Getting Pr[0] to Pr[-2N] vector
zf_Pr_col = zf_kTb(round(length(zf_kTb)/2):end); % Getting Pr[0] to Pr[2N] vector
Pr = toeplitz(zf_Pr_col, zf_Pr_row); % With kTb points we can build Toeplitz Matrix
Po = zeros(round(length(zf_kTb)/2), 1); % Creating Po vector to force neighbour pulses to 0
Po(round(length(Po)/2)) = 1;
Ck_zf = inv(Pr)*Po; % Calculating ZFE filter coefficients
% Applying ZFE filter to Rx kTb points:
zf_kTb_ZFE = conv(zf_kTb, Ck_zf, ‘same’);
% Plot 1
figure(1)
stem(zf_kTb, ‘color’, [0.8500 0.3250 0.0980]);
hold on
stem(zf_kTb_ZFE, ‘color’, [0.9290 0.6940 0.1250]);
hold off;
xlabel(‘Symbol spaced points (kTb)’); ylabel(‘Magnitude’);
legend(‘Rx points’,’ZFE points’,’Location’,’southeast’);
% Applying ZFE filter to Rx signal
x_rc_ch_zf = conv(x_rc_ch, Ck_zf, ‘same’);
% Plot 2
figure(2)
stem(tx, x, ‘k’);
hold on;
plot(tx_rc, x_rc, ‘color’, [0 0.4470 0.7410]);
plot(tx_rc, x_rc_ch, ‘color’, [0.8500 0.3250 0.0980]);
plot(tx_rc, x_rc_ch_zf, ‘color’, [0.9290 0.6940 0.1250]);
hold off;
xlabel(‘Time (ms)’); ylabel(‘Magnitude’);
legend(‘Data’,’Tx Signal’,’Rx Signal’,’ZFE Signal’,’Location’,’southeast’);
For the first figure, the equalyzer is working like it should, it is forcing the symbol spaced points(kTb) to zero.
But for the second figure, when the whole discretized pulse from the Rx signal goes through the same ZFE filter, it doesn’t get equalyzed back to something like the Tx signal, it just gets a little bit bigger on the peak.
So my doubt is, can we equalyze the Rx pulse with this type of equalization and plot the equalized pulse to something close to Tx signal ?Or does it just works for the points of symbol time ? filter, plot, zero-forcing MATLAB Answers — New Questions
PREP pipeline in EEGLAB is not working for me
Hi All,
I tried to run PREP pipeline on my EEG data. I managed to install the plug-in, and when click OK to run the pipeline, nothing happens (I check this from windows task manager CPU utilization percentage). I am using MATLAB R2023a. I had first installed the latest version (0.56.0) of PREP, but after it did not work, I went to install an earlier version (0.55.4) of it. But, it still is not working. I would appereciate it if you could help me figure out the problem here.Hi All,
I tried to run PREP pipeline on my EEG data. I managed to install the plug-in, and when click OK to run the pipeline, nothing happens (I check this from windows task manager CPU utilization percentage). I am using MATLAB R2023a. I had first installed the latest version (0.56.0) of PREP, but after it did not work, I went to install an earlier version (0.55.4) of it. But, it still is not working. I would appereciate it if you could help me figure out the problem here. Hi All,
I tried to run PREP pipeline on my EEG data. I managed to install the plug-in, and when click OK to run the pipeline, nothing happens (I check this from windows task manager CPU utilization percentage). I am using MATLAB R2023a. I had first installed the latest version (0.56.0) of PREP, but after it did not work, I went to install an earlier version (0.55.4) of it. But, it still is not working. I would appereciate it if you could help me figure out the problem here. eeglab, eeg, prep MATLAB Answers — New Questions
How to calculate the mean integrated curvature of an ellipsoid?
I am using the following code to compute the surface area, mean integrated curvature, and Euler characteristic of the ellipsoid parameterized by r(x,y). Here ‘x’ and ‘y’ represent the angles $theta$ and $phi$ in spherical coordinates. The code is
clc; clear;
%ellipsoid radii
a=value1; b=value2; c=value2;
syms x y
%parametric vector equation of the ellipsoid
r=[a*cos(y)*sin(x), b*sin(x)*sin(y), c*cos(x)];
%partial derivatives
r_x=diff(r,x);
r_xx=diff(r_x,x);
r_y=diff(r,y);
r_yy=diff(r_y,y);
r_xy=diff(r_x,y);
%normal vector to the surface at each point
n=cross(r_x,r_y)/norm(cross(r_x,r_y));
%coefficients of the second fundamental form
E=dot(r_x,r_x);
F=dot(r_x,r_y);
G=dot(r_y,r_y);
L=dot(r_xx,n);
M=dot(r_xy,n);
N=dot(r_yy,n);
A=E*G-F^2;
K=((E*N)+(G*L)-(2*F*M))/A;
H=(L*N-M^2)/A;
dA=sqrt(A);
dC=K*dA;
dX=H*dA;
%converting syms functions to matlab functions
dA_=matlabFunction(dA); dC_=matlabFunction(dC); dX_=matlabFunction(dX);
% numerical integration
S = integral2(dA_, 0, 2*pi, 0, pi); %total surface area
C = (1/2)*integral2(dC_, 0, 2*pi, 0, pi); % medium integrated curvature
X = (1/(2*pi))*integral2(dX_, 0, 2*pi, 0, pi); % Euler characteristics
S and X give me very well, but the problem is with C, which always gives me very small, of the order of 1e-16 to 1e-14, which is absurd since C must be of the order of 4*pi*r (for the case of a sphere a=b=c=r). Could someone tell me what is wrong?I am using the following code to compute the surface area, mean integrated curvature, and Euler characteristic of the ellipsoid parameterized by r(x,y). Here ‘x’ and ‘y’ represent the angles $theta$ and $phi$ in spherical coordinates. The code is
clc; clear;
%ellipsoid radii
a=value1; b=value2; c=value2;
syms x y
%parametric vector equation of the ellipsoid
r=[a*cos(y)*sin(x), b*sin(x)*sin(y), c*cos(x)];
%partial derivatives
r_x=diff(r,x);
r_xx=diff(r_x,x);
r_y=diff(r,y);
r_yy=diff(r_y,y);
r_xy=diff(r_x,y);
%normal vector to the surface at each point
n=cross(r_x,r_y)/norm(cross(r_x,r_y));
%coefficients of the second fundamental form
E=dot(r_x,r_x);
F=dot(r_x,r_y);
G=dot(r_y,r_y);
L=dot(r_xx,n);
M=dot(r_xy,n);
N=dot(r_yy,n);
A=E*G-F^2;
K=((E*N)+(G*L)-(2*F*M))/A;
H=(L*N-M^2)/A;
dA=sqrt(A);
dC=K*dA;
dX=H*dA;
%converting syms functions to matlab functions
dA_=matlabFunction(dA); dC_=matlabFunction(dC); dX_=matlabFunction(dX);
% numerical integration
S = integral2(dA_, 0, 2*pi, 0, pi); %total surface area
C = (1/2)*integral2(dC_, 0, 2*pi, 0, pi); % medium integrated curvature
X = (1/(2*pi))*integral2(dX_, 0, 2*pi, 0, pi); % Euler characteristics
S and X give me very well, but the problem is with C, which always gives me very small, of the order of 1e-16 to 1e-14, which is absurd since C must be of the order of 4*pi*r (for the case of a sphere a=b=c=r). Could someone tell me what is wrong? I am using the following code to compute the surface area, mean integrated curvature, and Euler characteristic of the ellipsoid parameterized by r(x,y). Here ‘x’ and ‘y’ represent the angles $theta$ and $phi$ in spherical coordinates. The code is
clc; clear;
%ellipsoid radii
a=value1; b=value2; c=value2;
syms x y
%parametric vector equation of the ellipsoid
r=[a*cos(y)*sin(x), b*sin(x)*sin(y), c*cos(x)];
%partial derivatives
r_x=diff(r,x);
r_xx=diff(r_x,x);
r_y=diff(r,y);
r_yy=diff(r_y,y);
r_xy=diff(r_x,y);
%normal vector to the surface at each point
n=cross(r_x,r_y)/norm(cross(r_x,r_y));
%coefficients of the second fundamental form
E=dot(r_x,r_x);
F=dot(r_x,r_y);
G=dot(r_y,r_y);
L=dot(r_xx,n);
M=dot(r_xy,n);
N=dot(r_yy,n);
A=E*G-F^2;
K=((E*N)+(G*L)-(2*F*M))/A;
H=(L*N-M^2)/A;
dA=sqrt(A);
dC=K*dA;
dX=H*dA;
%converting syms functions to matlab functions
dA_=matlabFunction(dA); dC_=matlabFunction(dC); dX_=matlabFunction(dX);
% numerical integration
S = integral2(dA_, 0, 2*pi, 0, pi); %total surface area
C = (1/2)*integral2(dC_, 0, 2*pi, 0, pi); % medium integrated curvature
X = (1/(2*pi))*integral2(dX_, 0, 2*pi, 0, pi); % Euler characteristics
S and X give me very well, but the problem is with C, which always gives me very small, of the order of 1e-16 to 1e-14, which is absurd since C must be of the order of 4*pi*r (for the case of a sphere a=b=c=r). Could someone tell me what is wrong? ellipsoid, curvature, surface, ellipsoidal fit MATLAB Answers — New Questions
Display the exact selected area by zooming in on a surface/image
Hi,
I have an uiaxes on a GUI (appdesigner) on which I draw a 2D surface with axis equal. When I zoom in by selecting an area, I’d like the area displayed to correspond exactly to the one selected (no more, no less). I had this behavior with MATLAB 2019/2020. However, since upgrading to version 2024, I’ve been able to zoom in, but the initial width/length aspect ratio of the displayed surface remains unchanged. As the background isn’t clickable, elongated surfaces are very difficult to manage.
Here’s an illustration and an attached .fig. I’ve tried changing the daspect and DataAspectRatioMode, but couldn’t get it right.
If anyone has a solution, I’d love to hear from you!
Thanks in advance.Hi,
I have an uiaxes on a GUI (appdesigner) on which I draw a 2D surface with axis equal. When I zoom in by selecting an area, I’d like the area displayed to correspond exactly to the one selected (no more, no less). I had this behavior with MATLAB 2019/2020. However, since upgrading to version 2024, I’ve been able to zoom in, but the initial width/length aspect ratio of the displayed surface remains unchanged. As the background isn’t clickable, elongated surfaces are very difficult to manage.
Here’s an illustration and an attached .fig. I’ve tried changing the daspect and DataAspectRatioMode, but couldn’t get it right.
If anyone has a solution, I’d love to hear from you!
Thanks in advance. Hi,
I have an uiaxes on a GUI (appdesigner) on which I draw a 2D surface with axis equal. When I zoom in by selecting an area, I’d like the area displayed to correspond exactly to the one selected (no more, no less). I had this behavior with MATLAB 2019/2020. However, since upgrading to version 2024, I’ve been able to zoom in, but the initial width/length aspect ratio of the displayed surface remains unchanged. As the background isn’t clickable, elongated surfaces are very difficult to manage.
Here’s an illustration and an attached .fig. I’ve tried changing the daspect and DataAspectRatioMode, but couldn’t get it right.
If anyone has a solution, I’d love to hear from you!
Thanks in advance. aspect ratio, zoom, uiaxes, axes, surface, daspect, aspect, image MATLAB Answers — New Questions
Difficulty Finding Hydrogen (H2) Properties for Gas Properties (G) Block
Hi everyone,
I’m having some trouble finding the different properties of Hydrogen (H2) that I need to set in the Gas Properties (G) block in Simscape. I’m hoping someone here can provide me with some guidance on how to approach this.
Can anyone recommend a resource or provide some tips on how to determine these properties for Hydrogen (H2)?
Any help would be greatly appreciated!
Thanks in advance,Hi everyone,
I’m having some trouble finding the different properties of Hydrogen (H2) that I need to set in the Gas Properties (G) block in Simscape. I’m hoping someone here can provide me with some guidance on how to approach this.
Can anyone recommend a resource or provide some tips on how to determine these properties for Hydrogen (H2)?
Any help would be greatly appreciated!
Thanks in advance, Hi everyone,
I’m having some trouble finding the different properties of Hydrogen (H2) that I need to set in the Gas Properties (G) block in Simscape. I’m hoping someone here can provide me with some guidance on how to approach this.
Can anyone recommend a resource or provide some tips on how to determine these properties for Hydrogen (H2)?
Any help would be greatly appreciated!
Thanks in advance, gasproperties, hydrogen, h2 MATLAB Answers — New Questions
How to change the altitude in UAV Package Delivery Example?
I am using the UAV Package Delivery Example to fly a drone on top of the buildings in the US City Block. Are the heights of the buildings have a finite value or they are assumed to be inifinity? How do i change the altitude of the UAV such that I can fly above the buildings?I am using the UAV Package Delivery Example to fly a drone on top of the buildings in the US City Block. Are the heights of the buildings have a finite value or they are assumed to be inifinity? How do i change the altitude of the UAV such that I can fly above the buildings? I am using the UAV Package Delivery Example to fly a drone on top of the buildings in the US City Block. Are the heights of the buildings have a finite value or they are assumed to be inifinity? How do i change the altitude of the UAV such that I can fly above the buildings? uav, package, delivery, simulink MATLAB Answers — New Questions
visboundaries/linewidth not rendering sharply when exporting figures
Hi everyone,
I am working with MATLAB to generate images that include segmentation lines (using visboundaries and viscircles) drawn over images. However, when I export these images (using saveas or print), the lines are not rendered sharply. Instead, they are much thicker. If I change the LineWidth to something like 0.5 a “halo”/outline effect appears around them. Interestingly, when I zoom into the figure manually within MATLAB and then export, the lines are much sharper.
I already tried a different export format, different dpi (max 1000) and changing the figure position to a higher zoom level.
Any idea on how to improve the export quality?
figure;
imshow(dicomData, [], ‘InitialMagnification’, ‘fit’);
title(sprintf(‘segmentation %s’, fileTitle), ‘Interpreter’, ‘none’);
hold on;
visboundaries(signalRoiMask, ‘Color’, ‘g’, ‘LineWidth’, 1);
visboundaries(lesionMask, ‘Color’, ‘m’, ‘LineWidth’, 1);
visboundaries(surroundingTissueMask, ‘Color’, ‘r’, ‘LineWidth’, 1);
visboundaries(phantomRoiMask, ‘Color’, ‘b’, ‘LineWidth’, 1);
viscircles(phantomCenter, phantomRadius, ‘EdgeColor’, ‘c’);
segmentationFile = fullfile(imageFolder, sprintf(‘segmentation_%s.png’, fileTitle));
print(‘-dpng’, segmentationFile, ‘-r600’);Hi everyone,
I am working with MATLAB to generate images that include segmentation lines (using visboundaries and viscircles) drawn over images. However, when I export these images (using saveas or print), the lines are not rendered sharply. Instead, they are much thicker. If I change the LineWidth to something like 0.5 a “halo”/outline effect appears around them. Interestingly, when I zoom into the figure manually within MATLAB and then export, the lines are much sharper.
I already tried a different export format, different dpi (max 1000) and changing the figure position to a higher zoom level.
Any idea on how to improve the export quality?
figure;
imshow(dicomData, [], ‘InitialMagnification’, ‘fit’);
title(sprintf(‘segmentation %s’, fileTitle), ‘Interpreter’, ‘none’);
hold on;
visboundaries(signalRoiMask, ‘Color’, ‘g’, ‘LineWidth’, 1);
visboundaries(lesionMask, ‘Color’, ‘m’, ‘LineWidth’, 1);
visboundaries(surroundingTissueMask, ‘Color’, ‘r’, ‘LineWidth’, 1);
visboundaries(phantomRoiMask, ‘Color’, ‘b’, ‘LineWidth’, 1);
viscircles(phantomCenter, phantomRadius, ‘EdgeColor’, ‘c’);
segmentationFile = fullfile(imageFolder, sprintf(‘segmentation_%s.png’, fileTitle));
print(‘-dpng’, segmentationFile, ‘-r600’); Hi everyone,
I am working with MATLAB to generate images that include segmentation lines (using visboundaries and viscircles) drawn over images. However, when I export these images (using saveas or print), the lines are not rendered sharply. Instead, they are much thicker. If I change the LineWidth to something like 0.5 a “halo”/outline effect appears around them. Interestingly, when I zoom into the figure manually within MATLAB and then export, the lines are much sharper.
I already tried a different export format, different dpi (max 1000) and changing the figure position to a higher zoom level.
Any idea on how to improve the export quality?
figure;
imshow(dicomData, [], ‘InitialMagnification’, ‘fit’);
title(sprintf(‘segmentation %s’, fileTitle), ‘Interpreter’, ‘none’);
hold on;
visboundaries(signalRoiMask, ‘Color’, ‘g’, ‘LineWidth’, 1);
visboundaries(lesionMask, ‘Color’, ‘m’, ‘LineWidth’, 1);
visboundaries(surroundingTissueMask, ‘Color’, ‘r’, ‘LineWidth’, 1);
visboundaries(phantomRoiMask, ‘Color’, ‘b’, ‘LineWidth’, 1);
viscircles(phantomCenter, phantomRadius, ‘EdgeColor’, ‘c’);
segmentationFile = fullfile(imageFolder, sprintf(‘segmentation_%s.png’, fileTitle));
print(‘-dpng’, segmentationFile, ‘-r600’); visboundaries, export quality, matlab MATLAB Answers — New Questions
Basic Matlab App deisnger question regarding the Component Library
Hi,
This is a very basic question but I coudln’t find information regarind my inquery.
I have multiple slider switches on the app designer and each of them has label/name. What I wanted to do is to count the number of slider switches that are on the app, then create the for loop to obtain the slider’s name then store them. Once it is stored then will display on the UITable.
I believe Matlab should have the ability to count them but I couldn’t find a document for it.Hi,
This is a very basic question but I coudln’t find information regarind my inquery.
I have multiple slider switches on the app designer and each of them has label/name. What I wanted to do is to count the number of slider switches that are on the app, then create the for loop to obtain the slider’s name then store them. Once it is stored then will display on the UITable.
I believe Matlab should have the ability to count them but I couldn’t find a document for it. Hi,
This is a very basic question but I coudln’t find information regarind my inquery.
I have multiple slider switches on the app designer and each of them has label/name. What I wanted to do is to count the number of slider switches that are on the app, then create the for loop to obtain the slider’s name then store them. Once it is stored then will display on the UITable.
I believe Matlab should have the ability to count them but I couldn’t find a document for it. appdesigner, matlab MATLAB Answers — New Questions
Problem related to GUI deployment
Hello everyone, I am developing a GUI using MATLAB App Designer 2022b for my project, in that i have included two simulink models and a MATLAB code for the result and that is working perfectly fine when i run it in the MATLAB environment. But when i tried to deploy the same as a standalone application, it is throwing error as "File Analysis is Stopped since my model has SoC blockset".
But i didn’t use any SoC blockset for the model, it only has normal To workspace, From Workspace, bit Concat, Data conversion and UDP send block(HDL coder) alone. I didn’t know why it shows such errors because of this i can’t deploy the app now. Somebody please help where did I go wrongHello everyone, I am developing a GUI using MATLAB App Designer 2022b for my project, in that i have included two simulink models and a MATLAB code for the result and that is working perfectly fine when i run it in the MATLAB environment. But when i tried to deploy the same as a standalone application, it is throwing error as "File Analysis is Stopped since my model has SoC blockset".
But i didn’t use any SoC blockset for the model, it only has normal To workspace, From Workspace, bit Concat, Data conversion and UDP send block(HDL coder) alone. I didn’t know why it shows such errors because of this i can’t deploy the app now. Somebody please help where did I go wrong Hello everyone, I am developing a GUI using MATLAB App Designer 2022b for my project, in that i have included two simulink models and a MATLAB code for the result and that is working perfectly fine when i run it in the MATLAB environment. But when i tried to deploy the same as a standalone application, it is throwing error as "File Analysis is Stopped since my model has SoC blockset".
But i didn’t use any SoC blockset for the model, it only has normal To workspace, From Workspace, bit Concat, Data conversion and UDP send block(HDL coder) alone. I didn’t know why it shows such errors because of this i can’t deploy the app now. Somebody please help where did I go wrong app designer, simulink, soc, matlab gui MATLAB Answers — New Questions
Why do I get an “Incorrect data type” error or “Parameter precision loss” warning when I try to tune a parameter with SLRT & Speedgoat?
I am trying to change a Gain parameter during my Simulink Real-Time (SLRT) simulation, but I get the following error when I use "setparam":
>> tg = slrealtime;
>> tg.setparam(‘MyModel/Gain’,’Gain’,-2)
Error using slrealtime.Target/throwErrorWithCause
Unable to set ‘Gain’ parameter value on target computer ‘TargetPC1’: Incorrect data type.
Error in slrealtime.Target/setparam (line 99)
this.throwErrorWithCause(‘slrealtime:target:setparamError’, …
Caused by:
Error using slrealtime.internal.ParameterTuning/setParamWork
Incorrect data type.
When I try changing the parameter in the block mask while using the external mode ("Run on Target"), I see warnings such as the following in the MATLAB prompt:
Warning: Parameter precision loss occurred for ‘Gain’ of ‘MyModel/Gain’. The
original value of the parameter, 1, cannot be represented exactly using the run-time data type
sfix32_En31. The value is quantized to 0.9999999995343387. Quantization error occurred with an absolute
difference of 4.656612873077393e-10 and a relative difference of 4.65661287307739e-08%.
Suggested Actions:
• To disable this warning or error for all parameters in the model, set the ‘Detect precision loss’
option to ‘none’. – Apply
• Inspect details in the Parameter Quantization Advisor. – Open
• – Suppress
> In slrealtime/Instrument/dataAvailableFromObserverViaTarget (line 1413)
In slrealtime.Target/dataAvailableFromObserver (line 66)
In slrealtime.Instrument>@(varargin)tg.dataAvailableFromObserver(varargin{:}) (line 1332)
In slrealtime.internal.instrument.StreamingCallBack.NewData (line 25)I am trying to change a Gain parameter during my Simulink Real-Time (SLRT) simulation, but I get the following error when I use "setparam":
>> tg = slrealtime;
>> tg.setparam(‘MyModel/Gain’,’Gain’,-2)
Error using slrealtime.Target/throwErrorWithCause
Unable to set ‘Gain’ parameter value on target computer ‘TargetPC1’: Incorrect data type.
Error in slrealtime.Target/setparam (line 99)
this.throwErrorWithCause(‘slrealtime:target:setparamError’, …
Caused by:
Error using slrealtime.internal.ParameterTuning/setParamWork
Incorrect data type.
When I try changing the parameter in the block mask while using the external mode ("Run on Target"), I see warnings such as the following in the MATLAB prompt:
Warning: Parameter precision loss occurred for ‘Gain’ of ‘MyModel/Gain’. The
original value of the parameter, 1, cannot be represented exactly using the run-time data type
sfix32_En31. The value is quantized to 0.9999999995343387. Quantization error occurred with an absolute
difference of 4.656612873077393e-10 and a relative difference of 4.65661287307739e-08%.
Suggested Actions:
• To disable this warning or error for all parameters in the model, set the ‘Detect precision loss’
option to ‘none’. – Apply
• Inspect details in the Parameter Quantization Advisor. – Open
• – Suppress
> In slrealtime/Instrument/dataAvailableFromObserverViaTarget (line 1413)
In slrealtime.Target/dataAvailableFromObserver (line 66)
In slrealtime.Instrument>@(varargin)tg.dataAvailableFromObserver(varargin{:}) (line 1332)
In slrealtime.internal.instrument.StreamingCallBack.NewData (line 25) I am trying to change a Gain parameter during my Simulink Real-Time (SLRT) simulation, but I get the following error when I use "setparam":
>> tg = slrealtime;
>> tg.setparam(‘MyModel/Gain’,’Gain’,-2)
Error using slrealtime.Target/throwErrorWithCause
Unable to set ‘Gain’ parameter value on target computer ‘TargetPC1’: Incorrect data type.
Error in slrealtime.Target/setparam (line 99)
this.throwErrorWithCause(‘slrealtime:target:setparamError’, …
Caused by:
Error using slrealtime.internal.ParameterTuning/setParamWork
Incorrect data type.
When I try changing the parameter in the block mask while using the external mode ("Run on Target"), I see warnings such as the following in the MATLAB prompt:
Warning: Parameter precision loss occurred for ‘Gain’ of ‘MyModel/Gain’. The
original value of the parameter, 1, cannot be represented exactly using the run-time data type
sfix32_En31. The value is quantized to 0.9999999995343387. Quantization error occurred with an absolute
difference of 4.656612873077393e-10 and a relative difference of 4.65661287307739e-08%.
Suggested Actions:
• To disable this warning or error for all parameters in the model, set the ‘Detect precision loss’
option to ‘none’. – Apply
• Inspect details in the Parameter Quantization Advisor. – Open
• – Suppress
> In slrealtime/Instrument/dataAvailableFromObserverViaTarget (line 1413)
In slrealtime.Target/dataAvailableFromObserver (line 66)
In slrealtime.Instrument>@(varargin)tg.dataAvailableFromObserver(varargin{:}) (line 1332)
In slrealtime.internal.instrument.StreamingCallBack.NewData (line 25) slrt, setparam, getparam MATLAB Answers — New Questions
Problem with Power system onramp course in simulink
you can see the error what can I do. all connection are ok.you can see the error what can I do. all connection are ok. you can see the error what can I do. all connection are ok. matlab simulation power system onramp course MATLAB Answers — New Questions
What is the ratio of area of the flame between the last frame and the first? What is wrong with my approach? I am getting an incorrect answer upon submission.
Question 3 Create a mask for each frame of this video that isolates the nearly-white flame exiting the rocket. Do this by converting each frame to grayscale. Then label all pixels with intensities less than or equal to 245 as false, and all pixels with intensities greater than 245 as true.
What is the ratio of area of the flame between the last frame and the first? (Use the number of true pixels for area.)
% Load the video file ‘shuttle.avi’
videoFile = ‘shuttle.avi’;
v = VideoReader(videoFile);
% Read the first frame
firstFrame = readFrame(v);
% Move to the last frame
while hasFrame(v)
lastFrame = readFrame(v);
end
% Convert both frames to grayscale
firstGray = rgb2gray(firstFrame);
lastGray = rgb2gray(lastFrame);
% Create masks where pixel intensities > 245 are true, the rest are false
firstMask = firstGray > 245;
lastMask = lastGray > 245;
% Calculate the flame area (number of ‘true’ pixels) for both frames
areaFirst = sum(firstMask(:));
areaLast = sum(lastMask(:));
% Calculate the ratio of the flame area between the last and the first frame
if areaFirst == 0
error(‘No flame detected in the first frame.’);
else
ratio = areaLast / areaFirst;
end
% Display the results
fprintf(‘Area of the flame in the first frame: %d pixelsn’, areaFirst);
fprintf(‘Area of the flame in the last frame: %d pixelsn’, areaLast);
fprintf(‘Ratio of flame area (last frame / first frame): %.2fn’, ratio);
% Optional: Display the original frames and the masks for visual verification
figure;
subplot(2,2,1), imshow(firstFrame), title(‘First Frame’);
subplot(2,2,2), imshow(lastFrame), title(‘Last Frame’);
subplot(2,2,3), imshow(firstMask), title(‘First Frame Mask’);
subplot(2,2,4), imshow(lastMask), title(‘Last Frame Mask’);Question 3 Create a mask for each frame of this video that isolates the nearly-white flame exiting the rocket. Do this by converting each frame to grayscale. Then label all pixels with intensities less than or equal to 245 as false, and all pixels with intensities greater than 245 as true.
What is the ratio of area of the flame between the last frame and the first? (Use the number of true pixels for area.)
% Load the video file ‘shuttle.avi’
videoFile = ‘shuttle.avi’;
v = VideoReader(videoFile);
% Read the first frame
firstFrame = readFrame(v);
% Move to the last frame
while hasFrame(v)
lastFrame = readFrame(v);
end
% Convert both frames to grayscale
firstGray = rgb2gray(firstFrame);
lastGray = rgb2gray(lastFrame);
% Create masks where pixel intensities > 245 are true, the rest are false
firstMask = firstGray > 245;
lastMask = lastGray > 245;
% Calculate the flame area (number of ‘true’ pixels) for both frames
areaFirst = sum(firstMask(:));
areaLast = sum(lastMask(:));
% Calculate the ratio of the flame area between the last and the first frame
if areaFirst == 0
error(‘No flame detected in the first frame.’);
else
ratio = areaLast / areaFirst;
end
% Display the results
fprintf(‘Area of the flame in the first frame: %d pixelsn’, areaFirst);
fprintf(‘Area of the flame in the last frame: %d pixelsn’, areaLast);
fprintf(‘Ratio of flame area (last frame / first frame): %.2fn’, ratio);
% Optional: Display the original frames and the masks for visual verification
figure;
subplot(2,2,1), imshow(firstFrame), title(‘First Frame’);
subplot(2,2,2), imshow(lastFrame), title(‘Last Frame’);
subplot(2,2,3), imshow(firstMask), title(‘First Frame Mask’);
subplot(2,2,4), imshow(lastMask), title(‘Last Frame Mask’); Question 3 Create a mask for each frame of this video that isolates the nearly-white flame exiting the rocket. Do this by converting each frame to grayscale. Then label all pixels with intensities less than or equal to 245 as false, and all pixels with intensities greater than 245 as true.
What is the ratio of area of the flame between the last frame and the first? (Use the number of true pixels for area.)
% Load the video file ‘shuttle.avi’
videoFile = ‘shuttle.avi’;
v = VideoReader(videoFile);
% Read the first frame
firstFrame = readFrame(v);
% Move to the last frame
while hasFrame(v)
lastFrame = readFrame(v);
end
% Convert both frames to grayscale
firstGray = rgb2gray(firstFrame);
lastGray = rgb2gray(lastFrame);
% Create masks where pixel intensities > 245 are true, the rest are false
firstMask = firstGray > 245;
lastMask = lastGray > 245;
% Calculate the flame area (number of ‘true’ pixels) for both frames
areaFirst = sum(firstMask(:));
areaLast = sum(lastMask(:));
% Calculate the ratio of the flame area between the last and the first frame
if areaFirst == 0
error(‘No flame detected in the first frame.’);
else
ratio = areaLast / areaFirst;
end
% Display the results
fprintf(‘Area of the flame in the first frame: %d pixelsn’, areaFirst);
fprintf(‘Area of the flame in the last frame: %d pixelsn’, areaLast);
fprintf(‘Ratio of flame area (last frame / first frame): %.2fn’, ratio);
% Optional: Display the original frames and the masks for visual verification
figure;
subplot(2,2,1), imshow(firstFrame), title(‘First Frame’);
subplot(2,2,2), imshow(lastFrame), title(‘Last Frame’);
subplot(2,2,3), imshow(firstMask), title(‘First Frame Mask’);
subplot(2,2,4), imshow(lastMask), title(‘Last Frame Mask’); image processing MATLAB Answers — New Questions
How to know what version of MKL is MATLAB using
Hi:
I am using MATLAB R2010b. I would like to know the version (I think there is a command but I don’t remember it) to know what version of MKL (Math Kernel Library) is MATLAB using.
Thank you very muchHi:
I am using MATLAB R2010b. I would like to know the version (I think there is a command but I don’t remember it) to know what version of MKL (Math Kernel Library) is MATLAB using.
Thank you very much Hi:
I am using MATLAB R2010b. I would like to know the version (I think there is a command but I don’t remember it) to know what version of MKL (Math Kernel Library) is MATLAB using.
Thank you very much mkl matlab MATLAB Answers — New Questions
Creating a Code to determine Lift Curve Slope
For an Aerodynamics couse, we need to create a code that computes lifting surfaces (wing) aerodynamics. I cannot get the graph to display a nice CL vs AoA curve, but only a single value. I don’t know how I can accomplish this. As I am a novice to MAtlab, I would appreciate some pointers or hints. Thank you.
clc;
% Default airfoil or not…
Default_AF = 0;
% A/F Characteristics:
% Lift coefficient [1/rad]:
Cl_alpha = 5.79;
Cl_alphaInRadians = deg2rad(Cl_alpha);
% Sectional lift curve slope [deg]:
alpha_0 = -2.0;
% Pitching moment [1/rad]:
Cm_alpha = 0;
Cm_alphaInRadians = deg2rad(Cm_alpha);
% 2D Pitching moment:
Cm_0 = -0.025;
% Coefficient in series expansion of circulation distribution [deg]:
alpha_nl = 8;
% Wing planform Geometry [inches]:
% [root-LE,root-TE,tip-LE,tip-TE]
x1 = 0;
y1 = 0;
x2 = 200;
y2 = 0;
x3 = 0;
y3 = 1000;
x4 = 200;
y4 = 1000;
% Wing twist angle [deg]:
theta_t = 0;
% Number of spanwise coefficients:
N = 100;
% Flight Conditions:
% Free-stream Velocity [ft/sec]
V = 100;
% Density [slugs/ft^3]:
rho = 0.002344;
% Viscous Force [lb.s/ft^2]
mu = 0.0000003737;
% Angle of Attack [deg]
alpha = 5;
% Wing span:
b = sqrt((x2-x1)^2 + (y2-y1)^2);
% Wing chord:
c = sqrt((x3-x1)^2 + (y3-y1)^2);
% Wing area:
S = b*c;
% Wing semi-span:
s = b/2;
% Aspect Ratio:
AR = b^2./S;
% Applying segment length of the wings:
alpha_segment = zeros(1,N);
theta_segment = zeros(1,N);
% Taper Ratio and its range within the wing (which is 0 to 1):
for lambda_r = 0:0.25:1
% Root Chord:
c_root = (2*S) / ((1+lambda_r)*b);
% Tip Chord:
c_tip = ((2*S)/((1+lambda_r)*b)) * (1-((2*(1-lambda_r))/b)*(b/2));
% Mean Aerodynamic Chord:
MAC = (2/3)*(c_root+c_tip-(c_root*c_tip)/(c_root+c_tip));
% Taper ratio:
lambda = c_tip / c_root;
% Providing segment limitation within range:
alpha_segment(1) = alpha;
theta_segment(1) = pi/2;
% Completing the Lifting Line Theory to determine the
% matrix value of the segments:
for N = 2:N
c(N) = c_root+(c_tip-c_root)/N.*N;
alpha_segment(N) = alpha+(theta_t)/N.*N;
theta_segment = pi/(2*N):pi/(2*N):pi/2;
end
% Lifting line theory construction:
xb = 4*b./(pi*c);
% Completing the [B] matrix:
for i = 1:N
for j = 1:N
B(i,j) = (sin(j.*theta_segment(i))).*(xb(i)+j/(sin(theta_segment(i))));
end
slope(i) = (alpha_segment(i)-alpha_0)*(pi/180);
end
A = Btranspose(slope);
end
% Leading edge sweep angle
for fai = 1:N
delta_LE(fai) = fai*(A(fai)/A(1))^2; %#ok<*SAGROW>
end
% Section Lift Coefficient of Airfoil
cl = 0.5*cos(pi/b);
% Wing Lift Coefficient:
CL = pi*AR*A(1);
% Span Efficiency:
delta = sum(delta_LE);
CD_0 = 1/(1+delta);
% Induced drag coefficient:
CD_i = CL.^2 / (pi*CD_0*AR);
% Speed of sound (assuming 20 degree dry air) [ft/sec]:
C = 1125.33;
% Mach Number:
M = V / C;
% Dynamic Pressure:
q = (0.5*rho*V^2);
% Pitching Moment Coefficient:
CM = M / q*S*c;
% Subsonic Lift:
alpha_inf = 2*pi*cos(delta_LE);
% 3D Lift Curve Slope of airfoil:
CL_alpha = 2*pi*A;
% Geometric Angle of Attack of Wing:
alpha = (alpha_inf)/(1+(alpha_inf)/(pi*AR));
%———————————————————-
% Wing lift coefficient (CL) vs Angle of Attack (alpha):
figure(1);
plot(alpha,CL,’-o’)
grid on
title(‘Wing lift coefficient (CL) vs Angle of Attack (alpha)’)
ylabel(‘Wing Lift Coefficient, CL’)
xlabel(‘Angle of Attack, alpha [deg]’)
% Pitching moment coefficient(CM) vs Angle of Attack (alpha):
figure(2);
plot(alpha,CM,’-o’)
grid on
title(‘Pitching moment coefficient(CM) vs Angle of Attack (alpha)’)
ylabel(‘Pitching Moment Coefficient, CM’)
xlabel(‘Angle of Attack, alpha [deg]’)
% Wing lift coefficient (CL) vs Induced drag coefficient (CD_i):
figure(3);
plot(CD_i,CL,’-o’)
grid on
title(‘Wing lift coefficient (CL) vs Induced drag coefficient (CD_i)’)
ylabel(‘Wing Lift Coefficient, CL’)
xlabel(‘Induced Drag Coefficient, CD_i’)For an Aerodynamics couse, we need to create a code that computes lifting surfaces (wing) aerodynamics. I cannot get the graph to display a nice CL vs AoA curve, but only a single value. I don’t know how I can accomplish this. As I am a novice to MAtlab, I would appreciate some pointers or hints. Thank you.
clc;
% Default airfoil or not…
Default_AF = 0;
% A/F Characteristics:
% Lift coefficient [1/rad]:
Cl_alpha = 5.79;
Cl_alphaInRadians = deg2rad(Cl_alpha);
% Sectional lift curve slope [deg]:
alpha_0 = -2.0;
% Pitching moment [1/rad]:
Cm_alpha = 0;
Cm_alphaInRadians = deg2rad(Cm_alpha);
% 2D Pitching moment:
Cm_0 = -0.025;
% Coefficient in series expansion of circulation distribution [deg]:
alpha_nl = 8;
% Wing planform Geometry [inches]:
% [root-LE,root-TE,tip-LE,tip-TE]
x1 = 0;
y1 = 0;
x2 = 200;
y2 = 0;
x3 = 0;
y3 = 1000;
x4 = 200;
y4 = 1000;
% Wing twist angle [deg]:
theta_t = 0;
% Number of spanwise coefficients:
N = 100;
% Flight Conditions:
% Free-stream Velocity [ft/sec]
V = 100;
% Density [slugs/ft^3]:
rho = 0.002344;
% Viscous Force [lb.s/ft^2]
mu = 0.0000003737;
% Angle of Attack [deg]
alpha = 5;
% Wing span:
b = sqrt((x2-x1)^2 + (y2-y1)^2);
% Wing chord:
c = sqrt((x3-x1)^2 + (y3-y1)^2);
% Wing area:
S = b*c;
% Wing semi-span:
s = b/2;
% Aspect Ratio:
AR = b^2./S;
% Applying segment length of the wings:
alpha_segment = zeros(1,N);
theta_segment = zeros(1,N);
% Taper Ratio and its range within the wing (which is 0 to 1):
for lambda_r = 0:0.25:1
% Root Chord:
c_root = (2*S) / ((1+lambda_r)*b);
% Tip Chord:
c_tip = ((2*S)/((1+lambda_r)*b)) * (1-((2*(1-lambda_r))/b)*(b/2));
% Mean Aerodynamic Chord:
MAC = (2/3)*(c_root+c_tip-(c_root*c_tip)/(c_root+c_tip));
% Taper ratio:
lambda = c_tip / c_root;
% Providing segment limitation within range:
alpha_segment(1) = alpha;
theta_segment(1) = pi/2;
% Completing the Lifting Line Theory to determine the
% matrix value of the segments:
for N = 2:N
c(N) = c_root+(c_tip-c_root)/N.*N;
alpha_segment(N) = alpha+(theta_t)/N.*N;
theta_segment = pi/(2*N):pi/(2*N):pi/2;
end
% Lifting line theory construction:
xb = 4*b./(pi*c);
% Completing the [B] matrix:
for i = 1:N
for j = 1:N
B(i,j) = (sin(j.*theta_segment(i))).*(xb(i)+j/(sin(theta_segment(i))));
end
slope(i) = (alpha_segment(i)-alpha_0)*(pi/180);
end
A = Btranspose(slope);
end
% Leading edge sweep angle
for fai = 1:N
delta_LE(fai) = fai*(A(fai)/A(1))^2; %#ok<*SAGROW>
end
% Section Lift Coefficient of Airfoil
cl = 0.5*cos(pi/b);
% Wing Lift Coefficient:
CL = pi*AR*A(1);
% Span Efficiency:
delta = sum(delta_LE);
CD_0 = 1/(1+delta);
% Induced drag coefficient:
CD_i = CL.^2 / (pi*CD_0*AR);
% Speed of sound (assuming 20 degree dry air) [ft/sec]:
C = 1125.33;
% Mach Number:
M = V / C;
% Dynamic Pressure:
q = (0.5*rho*V^2);
% Pitching Moment Coefficient:
CM = M / q*S*c;
% Subsonic Lift:
alpha_inf = 2*pi*cos(delta_LE);
% 3D Lift Curve Slope of airfoil:
CL_alpha = 2*pi*A;
% Geometric Angle of Attack of Wing:
alpha = (alpha_inf)/(1+(alpha_inf)/(pi*AR));
%———————————————————-
% Wing lift coefficient (CL) vs Angle of Attack (alpha):
figure(1);
plot(alpha,CL,’-o’)
grid on
title(‘Wing lift coefficient (CL) vs Angle of Attack (alpha)’)
ylabel(‘Wing Lift Coefficient, CL’)
xlabel(‘Angle of Attack, alpha [deg]’)
% Pitching moment coefficient(CM) vs Angle of Attack (alpha):
figure(2);
plot(alpha,CM,’-o’)
grid on
title(‘Pitching moment coefficient(CM) vs Angle of Attack (alpha)’)
ylabel(‘Pitching Moment Coefficient, CM’)
xlabel(‘Angle of Attack, alpha [deg]’)
% Wing lift coefficient (CL) vs Induced drag coefficient (CD_i):
figure(3);
plot(CD_i,CL,’-o’)
grid on
title(‘Wing lift coefficient (CL) vs Induced drag coefficient (CD_i)’)
ylabel(‘Wing Lift Coefficient, CL’)
xlabel(‘Induced Drag Coefficient, CD_i’) For an Aerodynamics couse, we need to create a code that computes lifting surfaces (wing) aerodynamics. I cannot get the graph to display a nice CL vs AoA curve, but only a single value. I don’t know how I can accomplish this. As I am a novice to MAtlab, I would appreciate some pointers or hints. Thank you.
clc;
% Default airfoil or not…
Default_AF = 0;
% A/F Characteristics:
% Lift coefficient [1/rad]:
Cl_alpha = 5.79;
Cl_alphaInRadians = deg2rad(Cl_alpha);
% Sectional lift curve slope [deg]:
alpha_0 = -2.0;
% Pitching moment [1/rad]:
Cm_alpha = 0;
Cm_alphaInRadians = deg2rad(Cm_alpha);
% 2D Pitching moment:
Cm_0 = -0.025;
% Coefficient in series expansion of circulation distribution [deg]:
alpha_nl = 8;
% Wing planform Geometry [inches]:
% [root-LE,root-TE,tip-LE,tip-TE]
x1 = 0;
y1 = 0;
x2 = 200;
y2 = 0;
x3 = 0;
y3 = 1000;
x4 = 200;
y4 = 1000;
% Wing twist angle [deg]:
theta_t = 0;
% Number of spanwise coefficients:
N = 100;
% Flight Conditions:
% Free-stream Velocity [ft/sec]
V = 100;
% Density [slugs/ft^3]:
rho = 0.002344;
% Viscous Force [lb.s/ft^2]
mu = 0.0000003737;
% Angle of Attack [deg]
alpha = 5;
% Wing span:
b = sqrt((x2-x1)^2 + (y2-y1)^2);
% Wing chord:
c = sqrt((x3-x1)^2 + (y3-y1)^2);
% Wing area:
S = b*c;
% Wing semi-span:
s = b/2;
% Aspect Ratio:
AR = b^2./S;
% Applying segment length of the wings:
alpha_segment = zeros(1,N);
theta_segment = zeros(1,N);
% Taper Ratio and its range within the wing (which is 0 to 1):
for lambda_r = 0:0.25:1
% Root Chord:
c_root = (2*S) / ((1+lambda_r)*b);
% Tip Chord:
c_tip = ((2*S)/((1+lambda_r)*b)) * (1-((2*(1-lambda_r))/b)*(b/2));
% Mean Aerodynamic Chord:
MAC = (2/3)*(c_root+c_tip-(c_root*c_tip)/(c_root+c_tip));
% Taper ratio:
lambda = c_tip / c_root;
% Providing segment limitation within range:
alpha_segment(1) = alpha;
theta_segment(1) = pi/2;
% Completing the Lifting Line Theory to determine the
% matrix value of the segments:
for N = 2:N
c(N) = c_root+(c_tip-c_root)/N.*N;
alpha_segment(N) = alpha+(theta_t)/N.*N;
theta_segment = pi/(2*N):pi/(2*N):pi/2;
end
% Lifting line theory construction:
xb = 4*b./(pi*c);
% Completing the [B] matrix:
for i = 1:N
for j = 1:N
B(i,j) = (sin(j.*theta_segment(i))).*(xb(i)+j/(sin(theta_segment(i))));
end
slope(i) = (alpha_segment(i)-alpha_0)*(pi/180);
end
A = Btranspose(slope);
end
% Leading edge sweep angle
for fai = 1:N
delta_LE(fai) = fai*(A(fai)/A(1))^2; %#ok<*SAGROW>
end
% Section Lift Coefficient of Airfoil
cl = 0.5*cos(pi/b);
% Wing Lift Coefficient:
CL = pi*AR*A(1);
% Span Efficiency:
delta = sum(delta_LE);
CD_0 = 1/(1+delta);
% Induced drag coefficient:
CD_i = CL.^2 / (pi*CD_0*AR);
% Speed of sound (assuming 20 degree dry air) [ft/sec]:
C = 1125.33;
% Mach Number:
M = V / C;
% Dynamic Pressure:
q = (0.5*rho*V^2);
% Pitching Moment Coefficient:
CM = M / q*S*c;
% Subsonic Lift:
alpha_inf = 2*pi*cos(delta_LE);
% 3D Lift Curve Slope of airfoil:
CL_alpha = 2*pi*A;
% Geometric Angle of Attack of Wing:
alpha = (alpha_inf)/(1+(alpha_inf)/(pi*AR));
%———————————————————-
% Wing lift coefficient (CL) vs Angle of Attack (alpha):
figure(1);
plot(alpha,CL,’-o’)
grid on
title(‘Wing lift coefficient (CL) vs Angle of Attack (alpha)’)
ylabel(‘Wing Lift Coefficient, CL’)
xlabel(‘Angle of Attack, alpha [deg]’)
% Pitching moment coefficient(CM) vs Angle of Attack (alpha):
figure(2);
plot(alpha,CM,’-o’)
grid on
title(‘Pitching moment coefficient(CM) vs Angle of Attack (alpha)’)
ylabel(‘Pitching Moment Coefficient, CM’)
xlabel(‘Angle of Attack, alpha [deg]’)
% Wing lift coefficient (CL) vs Induced drag coefficient (CD_i):
figure(3);
plot(CD_i,CL,’-o’)
grid on
title(‘Wing lift coefficient (CL) vs Induced drag coefficient (CD_i)’)
ylabel(‘Wing Lift Coefficient, CL’)
xlabel(‘Induced Drag Coefficient, CD_i’) aerodynamics, lifting surfaces MATLAB Answers — New Questions
4. f(x)=x^2/3(3-x^2)(x-4). how do i enter this function in matlab.
When I input the above function as x^(2/3)*(3-x^2)*(x-4) in a code where i have to find extrema , maxima and critical points for a given function , i am getting error which says
Warning: Solutions are parameterized by the symbols: z2. To include parameters and conditions in the solution, specify the ‘ReturnConditions’
value as ‘true’.
Error using mupadengine/feval2char
Unable to convert expression containing symbolic variables into double array. Apply ‘subs’ function first to substitute values for variables.
Error in sym/double (line 755)
Xstr = feval2char(symengine, "symobj::double", S);
however the same cose is working if I input some other functionWhen I input the above function as x^(2/3)*(3-x^2)*(x-4) in a code where i have to find extrema , maxima and critical points for a given function , i am getting error which says
Warning: Solutions are parameterized by the symbols: z2. To include parameters and conditions in the solution, specify the ‘ReturnConditions’
value as ‘true’.
Error using mupadengine/feval2char
Unable to convert expression containing symbolic variables into double array. Apply ‘subs’ function first to substitute values for variables.
Error in sym/double (line 755)
Xstr = feval2char(symengine, "symobj::double", S);
however the same cose is working if I input some other function When I input the above function as x^(2/3)*(3-x^2)*(x-4) in a code where i have to find extrema , maxima and critical points for a given function , i am getting error which says
Warning: Solutions are parameterized by the symbols: z2. To include parameters and conditions in the solution, specify the ‘ReturnConditions’
value as ‘true’.
Error using mupadengine/feval2char
Unable to convert expression containing symbolic variables into double array. Apply ‘subs’ function first to substitute values for variables.
Error in sym/double (line 755)
Xstr = feval2char(symengine, "symobj::double", S);
however the same cose is working if I input some other function please do clear this problem MATLAB Answers — New Questions
Why do I get a blank SSO screen when attempting to sign in to MATLAB at start up?
I was able to install MATLAB, however I am not able to sign into my MathWorks Account with my university credentials when trying to launch MATLAB for the first time.
When I input my email address it says I must log in through my school’s portal, but nothing pops up except a blank white page in my shortcut.
I was able to install MATLAB, however I am not able to sign into my MathWorks Account with my university credentials when trying to launch MATLAB for the first time.
When I input my email address it says I must log in through my school’s portal, but nothing pops up except a blank white page in my shortcut.
I was able to install MATLAB, however I am not able to sign into my MathWorks Account with my university credentials when trying to launch MATLAB for the first time.
When I input my email address it says I must log in through my school’s portal, but nothing pops up except a blank white page in my shortcut.
MATLAB Answers — New Questions
Determine the direction of travelling waves in Fourier Analysis
% I am conducting a FFT analysis and i I observed that there is travelling
% wave. Please, how do I determine the direction of the travelling waves?
% Compute the phase of the FFT: theta_phase = angle(Ytheta);
% Compute the mean phase difference: p = polyfit(f, theta_phase, 1);
% slope = p(1); % The slope of the phase vs. frequency plot
% Store the mean phase difference: mean_phase_diff(i) = slope;
% Then I test the mean_phase_diff(i) > 0 implies rightward direction or if
% mean_phase_diff(i) < 0 leftward direction. I am wondering if there is a
% better way or function to do this.
clear
%close all
pars.W = 20e-6;
pars.D = 2e-6;
% time discretisation – start, step and end
t = 0:0.025:5;
% Extract theta data
loaded_data = load(‘thetam.mat’);
thetam = loaded_data.thetam;
% Sample frequency
Fs = 1/(t(2) – t(1));
% Number of samples
L = length(t);
% Number of ramp slopes
num_ramp_slopes = size(thetam, 1);
% Frequency vector for FFT
f = (-L/2 : L/2-1) * (Fs / L);
% Loop through each ramp_slope
for i = 1:num_ramp_slopes
% Extract the theta data for the current ramp_slope
theta_data = thetam(i, :);
% Compute the FFT of the theta data
Ytheta = fft(theta_data);
% Shift zero frequency component to center
Ytheta = fftshift(Ytheta);
end
% Plot the magnitude of the FFT for the first ramp_slope
fig1 = figure;
plot(f, abs(fftshift(fft(thetam(1, :)))), ‘LineWidth’, 0.8);
xlabel(‘Frequency (Hz)’);
ylabel(‘Magnitude’);
title(‘FFT Magnitude for Ramp Slope 1’);
xlim([-Fs/2 Fs/2]);
grid on;% I am conducting a FFT analysis and i I observed that there is travelling
% wave. Please, how do I determine the direction of the travelling waves?
% Compute the phase of the FFT: theta_phase = angle(Ytheta);
% Compute the mean phase difference: p = polyfit(f, theta_phase, 1);
% slope = p(1); % The slope of the phase vs. frequency plot
% Store the mean phase difference: mean_phase_diff(i) = slope;
% Then I test the mean_phase_diff(i) > 0 implies rightward direction or if
% mean_phase_diff(i) < 0 leftward direction. I am wondering if there is a
% better way or function to do this.
clear
%close all
pars.W = 20e-6;
pars.D = 2e-6;
% time discretisation – start, step and end
t = 0:0.025:5;
% Extract theta data
loaded_data = load(‘thetam.mat’);
thetam = loaded_data.thetam;
% Sample frequency
Fs = 1/(t(2) – t(1));
% Number of samples
L = length(t);
% Number of ramp slopes
num_ramp_slopes = size(thetam, 1);
% Frequency vector for FFT
f = (-L/2 : L/2-1) * (Fs / L);
% Loop through each ramp_slope
for i = 1:num_ramp_slopes
% Extract the theta data for the current ramp_slope
theta_data = thetam(i, :);
% Compute the FFT of the theta data
Ytheta = fft(theta_data);
% Shift zero frequency component to center
Ytheta = fftshift(Ytheta);
end
% Plot the magnitude of the FFT for the first ramp_slope
fig1 = figure;
plot(f, abs(fftshift(fft(thetam(1, :)))), ‘LineWidth’, 0.8);
xlabel(‘Frequency (Hz)’);
ylabel(‘Magnitude’);
title(‘FFT Magnitude for Ramp Slope 1’);
xlim([-Fs/2 Fs/2]);
grid on; % I am conducting a FFT analysis and i I observed that there is travelling
% wave. Please, how do I determine the direction of the travelling waves?
% Compute the phase of the FFT: theta_phase = angle(Ytheta);
% Compute the mean phase difference: p = polyfit(f, theta_phase, 1);
% slope = p(1); % The slope of the phase vs. frequency plot
% Store the mean phase difference: mean_phase_diff(i) = slope;
% Then I test the mean_phase_diff(i) > 0 implies rightward direction or if
% mean_phase_diff(i) < 0 leftward direction. I am wondering if there is a
% better way or function to do this.
clear
%close all
pars.W = 20e-6;
pars.D = 2e-6;
% time discretisation – start, step and end
t = 0:0.025:5;
% Extract theta data
loaded_data = load(‘thetam.mat’);
thetam = loaded_data.thetam;
% Sample frequency
Fs = 1/(t(2) – t(1));
% Number of samples
L = length(t);
% Number of ramp slopes
num_ramp_slopes = size(thetam, 1);
% Frequency vector for FFT
f = (-L/2 : L/2-1) * (Fs / L);
% Loop through each ramp_slope
for i = 1:num_ramp_slopes
% Extract the theta data for the current ramp_slope
theta_data = thetam(i, :);
% Compute the FFT of the theta data
Ytheta = fft(theta_data);
% Shift zero frequency component to center
Ytheta = fftshift(Ytheta);
end
% Plot the magnitude of the FFT for the first ramp_slope
fig1 = figure;
plot(f, abs(fftshift(fft(thetam(1, :)))), ‘LineWidth’, 0.8);
xlabel(‘Frequency (Hz)’);
ylabel(‘Magnitude’);
title(‘FFT Magnitude for Ramp Slope 1’);
xlim([-Fs/2 Fs/2]);
grid on; wave direction, fourier series, fft MATLAB Answers — New Questions
how can I take Dynamic Voltage Restorer Block from library browser in matlab simulink ?
I am searching the Dynamic Voltage Restorer (DVR) block in library browser but I am not getting the block.please provide me the steps to find out the DVR block from library browser in matlab simulink.I am searching the Dynamic Voltage Restorer (DVR) block in library browser but I am not getting the block.please provide me the steps to find out the DVR block from library browser in matlab simulink. I am searching the Dynamic Voltage Restorer (DVR) block in library browser but I am not getting the block.please provide me the steps to find out the DVR block from library browser in matlab simulink. dvr MATLAB Answers — New Questions