Category: Matlab
Category Archives: Matlab
I am having difficulty in modeling 1D SOFC stack model
Hello ,
I am trying to develop a 1D SOFC model based on FDM or FVM based discretization. but SOFC stack has many sub-models and all are connected in real time how would i start ? what would be my modeling strategy ( scriipt or Simulink ) and how i break my task?
such as electrical sub model , chemcial and electrochemical sub model , mass conseration , and species conservation ?Hello ,
I am trying to develop a 1D SOFC model based on FDM or FVM based discretization. but SOFC stack has many sub-models and all are connected in real time how would i start ? what would be my modeling strategy ( scriipt or Simulink ) and how i break my task?
such as electrical sub model , chemcial and electrochemical sub model , mass conseration , and species conservation ? Hello ,
I am trying to develop a 1D SOFC model based on FDM or FVM based discretization. but SOFC stack has many sub-models and all are connected in real time how would i start ? what would be my modeling strategy ( scriipt or Simulink ) and how i break my task?
such as electrical sub model , chemcial and electrochemical sub model , mass conseration , and species conservation ? sofc, sofc model MATLAB Answers — New Questions
Does enu2ecefv make any assumptions about the ellipsoid?
From my understanding of the formula, the parameters for the ellipsoid (semimajor axes, flattening, etc.) are not taken into account at all in the calculation. Does this calculation assume a spherical body? Does this only work for the WGS84 Earth ellipsoid? Or is it independent of the ellipsoid?From my understanding of the formula, the parameters for the ellipsoid (semimajor axes, flattening, etc.) are not taken into account at all in the calculation. Does this calculation assume a spherical body? Does this only work for the WGS84 Earth ellipsoid? Or is it independent of the ellipsoid? From my understanding of the formula, the parameters for the ellipsoid (semimajor axes, flattening, etc.) are not taken into account at all in the calculation. Does this calculation assume a spherical body? Does this only work for the WGS84 Earth ellipsoid? Or is it independent of the ellipsoid? ellipsoid, coordinate conversions, enu2ecefv, vectors MATLAB Answers — New Questions
how does this equation solve for x? it’s the intersection between a line and a hyperbola – hopefully
s*x+i = (x^2*v^2/w^2+v^2)^(1/2)s*x+i = (x^2*v^2/w^2+v^2)^(1/2) s*x+i = (x^2*v^2/w^2+v^2)^(1/2) hyperbola interection MATLAB Answers — New Questions
REGARDING THE PLOT IN MATHLAB2TIKZ
x = -5:0.2:5;
t = 0:0.02:1;
C1 = sin(x’ * t); % Example data
surf(x, t, C1);
xlabel(‘x’);
ylabel(‘t’);
zlabel(‘eta(x,t)’);
title(‘Surface Plot of eta(x,t)’);
% Export the plot as a TikZ file
matlab2tikz(‘figure1.tikz’, ‘height’, ‘figureheight’, ‘width’, ‘figurewidth’);
%%%%%%%%%%%%%%%%%%%%%%%%%%55
WHENEVER I USE THE matlab2tikz THE FIGURE IS GENRATE FOR THE FIRST COMMAND BUT USING MATLAB2TIKZ IT IS THE FOLLOWING MSG IS DISPLAYED
You will need pgfplots version 1.12 or newer to compile the TikZ output
Do i need to install pgfplot in MATLAB .If yes how ?x = -5:0.2:5;
t = 0:0.02:1;
C1 = sin(x’ * t); % Example data
surf(x, t, C1);
xlabel(‘x’);
ylabel(‘t’);
zlabel(‘eta(x,t)’);
title(‘Surface Plot of eta(x,t)’);
% Export the plot as a TikZ file
matlab2tikz(‘figure1.tikz’, ‘height’, ‘figureheight’, ‘width’, ‘figurewidth’);
%%%%%%%%%%%%%%%%%%%%%%%%%%55
WHENEVER I USE THE matlab2tikz THE FIGURE IS GENRATE FOR THE FIRST COMMAND BUT USING MATLAB2TIKZ IT IS THE FOLLOWING MSG IS DISPLAYED
You will need pgfplots version 1.12 or newer to compile the TikZ output
Do i need to install pgfplot in MATLAB .If yes how ? x = -5:0.2:5;
t = 0:0.02:1;
C1 = sin(x’ * t); % Example data
surf(x, t, C1);
xlabel(‘x’);
ylabel(‘t’);
zlabel(‘eta(x,t)’);
title(‘Surface Plot of eta(x,t)’);
% Export the plot as a TikZ file
matlab2tikz(‘figure1.tikz’, ‘height’, ‘figureheight’, ‘width’, ‘figurewidth’);
%%%%%%%%%%%%%%%%%%%%%%%%%%55
WHENEVER I USE THE matlab2tikz THE FIGURE IS GENRATE FOR THE FIRST COMMAND BUT USING MATLAB2TIKZ IT IS THE FOLLOWING MSG IS DISPLAYED
You will need pgfplots version 1.12 or newer to compile the TikZ output
Do i need to install pgfplot in MATLAB .If yes how ? matlab2tikz MATLAB Answers — New Questions
Prediction time NN on STM board
Good morning All,
I would need to compare the computational times required by a NN to process a fixed length signal (3 channels- length: 516 elements) onboard of a STM microcontroller.
For this reason, I created a model with:
a fromworkspace block to collect three fixed length signals,
a stateful-regression-predict block( that recalls the NNs stored in a .mat file)
a simout block (please check the attached figure).
As I need to specify timestamps for each time-step of the sequence, I provide data as 516×4 array (first column is the specified time, the other three columns are the three channels of the input signal). This results in the model predicting the output at the corresponding timestamps with real-time. However, I would like to know the time that the NN takes to process the entire signals not in real-time, just as it was a simulation run on the STM board.
Do you have any clue on how to achieve this result?
I tried to check the "Measure task execution time" option in Hardware Settings/Code Generation/Verification. However, an error "Code generation information file does not exist." displayed while deployng the model to the STM Nucloeo board. It came out the this is a bug of Versione 2022 and 2023. Therefore, I switched to Version 2021, however, even if the model was deployed, once I opened the Data Inspector but no information about execution time is reported. Do you know any viable workaround?
Many thanks in advance
Best regards,
GiovanniGood morning All,
I would need to compare the computational times required by a NN to process a fixed length signal (3 channels- length: 516 elements) onboard of a STM microcontroller.
For this reason, I created a model with:
a fromworkspace block to collect three fixed length signals,
a stateful-regression-predict block( that recalls the NNs stored in a .mat file)
a simout block (please check the attached figure).
As I need to specify timestamps for each time-step of the sequence, I provide data as 516×4 array (first column is the specified time, the other three columns are the three channels of the input signal). This results in the model predicting the output at the corresponding timestamps with real-time. However, I would like to know the time that the NN takes to process the entire signals not in real-time, just as it was a simulation run on the STM board.
Do you have any clue on how to achieve this result?
I tried to check the "Measure task execution time" option in Hardware Settings/Code Generation/Verification. However, an error "Code generation information file does not exist." displayed while deployng the model to the STM Nucloeo board. It came out the this is a bug of Versione 2022 and 2023. Therefore, I switched to Version 2021, however, even if the model was deployed, once I opened the Data Inspector but no information about execution time is reported. Do you know any viable workaround?
Many thanks in advance
Best regards,
Giovanni Good morning All,
I would need to compare the computational times required by a NN to process a fixed length signal (3 channels- length: 516 elements) onboard of a STM microcontroller.
For this reason, I created a model with:
a fromworkspace block to collect three fixed length signals,
a stateful-regression-predict block( that recalls the NNs stored in a .mat file)
a simout block (please check the attached figure).
As I need to specify timestamps for each time-step of the sequence, I provide data as 516×4 array (first column is the specified time, the other three columns are the three channels of the input signal). This results in the model predicting the output at the corresponding timestamps with real-time. However, I would like to know the time that the NN takes to process the entire signals not in real-time, just as it was a simulation run on the STM board.
Do you have any clue on how to achieve this result?
I tried to check the "Measure task execution time" option in Hardware Settings/Code Generation/Verification. However, an error "Code generation information file does not exist." displayed while deployng the model to the STM Nucloeo board. It came out the this is a bug of Versione 2022 and 2023. Therefore, I switched to Version 2021, however, even if the model was deployed, once I opened the Data Inspector but no information about execution time is reported. Do you know any viable workaround?
Many thanks in advance
Best regards,
Giovanni time profiler, stm32 nucleo board MATLAB Answers — New Questions
How to get a dlgradient result for a blackbox function
I’m working on a tomography reconstruction code using a neural representation, which I’d like to train. After some debugging I discovered that:
(1) you can’t use the dlarrays as input to the radon() function;
(2) dlgradient will not work with untraced variables, therefore all variables must be dlarrays;
(3) Using extractdata() to get the input of the radon() function converted to double will fail because dlgradient will lose its trace.
So now I have a conundrum. I need to compute that gradient. dlgradient() won’t do the job. What’s the best alternative way to do it and have the same format as adamupdate() requires?
See below what my loss function looks like. The way it’s written now it will fail at the Sinogram=radon()… line, because Intensity is a dlarray(). As I previously said, if you fix that by extracting the data, then dlgradient() fails.
Thoughts would be appreciated.
function [loss, gradients]=modelLoss(net, XY, Mask, SinogramRef, theta)
Intensity = predict(net,XY);
Intensity = reshape(Intensity, size(Mask));
Intensity(Mask)=0;
Sinogram=radon(Intensity, theta);
Sinogram=dlarray(Sinogram);
loss = sum((Sinogram(~Mask)-SinogramRef(~Mask)).^2);
loss = loss / sum(~Mask(:));
gradients = dlgradient(loss,net.Learnables);
endI’m working on a tomography reconstruction code using a neural representation, which I’d like to train. After some debugging I discovered that:
(1) you can’t use the dlarrays as input to the radon() function;
(2) dlgradient will not work with untraced variables, therefore all variables must be dlarrays;
(3) Using extractdata() to get the input of the radon() function converted to double will fail because dlgradient will lose its trace.
So now I have a conundrum. I need to compute that gradient. dlgradient() won’t do the job. What’s the best alternative way to do it and have the same format as adamupdate() requires?
See below what my loss function looks like. The way it’s written now it will fail at the Sinogram=radon()… line, because Intensity is a dlarray(). As I previously said, if you fix that by extracting the data, then dlgradient() fails.
Thoughts would be appreciated.
function [loss, gradients]=modelLoss(net, XY, Mask, SinogramRef, theta)
Intensity = predict(net,XY);
Intensity = reshape(Intensity, size(Mask));
Intensity(Mask)=0;
Sinogram=radon(Intensity, theta);
Sinogram=dlarray(Sinogram);
loss = sum((Sinogram(~Mask)-SinogramRef(~Mask)).^2);
loss = loss / sum(~Mask(:));
gradients = dlgradient(loss,net.Learnables);
end I’m working on a tomography reconstruction code using a neural representation, which I’d like to train. After some debugging I discovered that:
(1) you can’t use the dlarrays as input to the radon() function;
(2) dlgradient will not work with untraced variables, therefore all variables must be dlarrays;
(3) Using extractdata() to get the input of the radon() function converted to double will fail because dlgradient will lose its trace.
So now I have a conundrum. I need to compute that gradient. dlgradient() won’t do the job. What’s the best alternative way to do it and have the same format as adamupdate() requires?
See below what my loss function looks like. The way it’s written now it will fail at the Sinogram=radon()… line, because Intensity is a dlarray(). As I previously said, if you fix that by extracting the data, then dlgradient() fails.
Thoughts would be appreciated.
function [loss, gradients]=modelLoss(net, XY, Mask, SinogramRef, theta)
Intensity = predict(net,XY);
Intensity = reshape(Intensity, size(Mask));
Intensity(Mask)=0;
Sinogram=radon(Intensity, theta);
Sinogram=dlarray(Sinogram);
loss = sum((Sinogram(~Mask)-SinogramRef(~Mask)).^2);
loss = loss / sum(~Mask(:));
gradients = dlgradient(loss,net.Learnables);
end deep learning, neural network, radon MATLAB Answers — New Questions
What are the differences between fitrnet and trainnet?
I am trying to perform regression on a set of data X (size 52048 x 4) with responses Y (size 52048 x 1).
If I perform a linear regression using mvregress(X,Y), I get a model with a coefficient of determination of 0.70.
If I train a neural network using fitrnet(X,Y), I get a model with a coefficient of determination of about 0.75.
mdl2 = fitrnet(X,Y);
I would like more customizability than what fitrnet offers, so I am trying to use trainnet. To make sure that I am using it correctly, I wanted to recreate the result from fitrnet using trainnet, so I set up the trainnet input parameters to match the defaults from fitrnet:
layers = [
featureInputLayer(size(X,2))
fullyConnectedLayer(10)
reluLayer
fullyConnectedLayer(1)];
options = trainingOptions(‘lbfgs’, GradientTolerance=1e-6, StepTolerance=1e-6);
mdl3 = trainnet(X,Y,layers,’mse’,options);
When I run this, after a few iterations I get a "Training stopped" message and the output model has a coefficient of determination less than 0.30. Sometimes the stoppage message says "Step tolerance reached" and sometimes it says "Suitable learning rate not found".
However, if I initialize the weights and biases for trainnet using the weights and biases learned by fitrnet, trainnet immediately recognizes this as an optimal solution and outputs "Training stopped: Suitable learning rate not found" without making any modification to the weights or biases.
layers = [
featureInputLayer(size(X,2))
fullyConnectedLayer(10, ‘Weights’, mdl2.LayerWeights{1}, ‘Bias’, mdl2.LayerBiases{1})
reluLayer
fullyConnectedLayer(1, ‘Weights’, mdl2.LayerWeights{2}, ‘Bias’, mdl2.LayerBiases{2})];
mdl4 = trainnet(X,Y,layers,’mse’,options);
How is it that trainnet can recognize the solution from fitrnet as optimal, but cannot recreate a similar result using what seems to be identical input parameters?I am trying to perform regression on a set of data X (size 52048 x 4) with responses Y (size 52048 x 1).
If I perform a linear regression using mvregress(X,Y), I get a model with a coefficient of determination of 0.70.
If I train a neural network using fitrnet(X,Y), I get a model with a coefficient of determination of about 0.75.
mdl2 = fitrnet(X,Y);
I would like more customizability than what fitrnet offers, so I am trying to use trainnet. To make sure that I am using it correctly, I wanted to recreate the result from fitrnet using trainnet, so I set up the trainnet input parameters to match the defaults from fitrnet:
layers = [
featureInputLayer(size(X,2))
fullyConnectedLayer(10)
reluLayer
fullyConnectedLayer(1)];
options = trainingOptions(‘lbfgs’, GradientTolerance=1e-6, StepTolerance=1e-6);
mdl3 = trainnet(X,Y,layers,’mse’,options);
When I run this, after a few iterations I get a "Training stopped" message and the output model has a coefficient of determination less than 0.30. Sometimes the stoppage message says "Step tolerance reached" and sometimes it says "Suitable learning rate not found".
However, if I initialize the weights and biases for trainnet using the weights and biases learned by fitrnet, trainnet immediately recognizes this as an optimal solution and outputs "Training stopped: Suitable learning rate not found" without making any modification to the weights or biases.
layers = [
featureInputLayer(size(X,2))
fullyConnectedLayer(10, ‘Weights’, mdl2.LayerWeights{1}, ‘Bias’, mdl2.LayerBiases{1})
reluLayer
fullyConnectedLayer(1, ‘Weights’, mdl2.LayerWeights{2}, ‘Bias’, mdl2.LayerBiases{2})];
mdl4 = trainnet(X,Y,layers,’mse’,options);
How is it that trainnet can recognize the solution from fitrnet as optimal, but cannot recreate a similar result using what seems to be identical input parameters? I am trying to perform regression on a set of data X (size 52048 x 4) with responses Y (size 52048 x 1).
If I perform a linear regression using mvregress(X,Y), I get a model with a coefficient of determination of 0.70.
If I train a neural network using fitrnet(X,Y), I get a model with a coefficient of determination of about 0.75.
mdl2 = fitrnet(X,Y);
I would like more customizability than what fitrnet offers, so I am trying to use trainnet. To make sure that I am using it correctly, I wanted to recreate the result from fitrnet using trainnet, so I set up the trainnet input parameters to match the defaults from fitrnet:
layers = [
featureInputLayer(size(X,2))
fullyConnectedLayer(10)
reluLayer
fullyConnectedLayer(1)];
options = trainingOptions(‘lbfgs’, GradientTolerance=1e-6, StepTolerance=1e-6);
mdl3 = trainnet(X,Y,layers,’mse’,options);
When I run this, after a few iterations I get a "Training stopped" message and the output model has a coefficient of determination less than 0.30. Sometimes the stoppage message says "Step tolerance reached" and sometimes it says "Suitable learning rate not found".
However, if I initialize the weights and biases for trainnet using the weights and biases learned by fitrnet, trainnet immediately recognizes this as an optimal solution and outputs "Training stopped: Suitable learning rate not found" without making any modification to the weights or biases.
layers = [
featureInputLayer(size(X,2))
fullyConnectedLayer(10, ‘Weights’, mdl2.LayerWeights{1}, ‘Bias’, mdl2.LayerBiases{1})
reluLayer
fullyConnectedLayer(1, ‘Weights’, mdl2.LayerWeights{2}, ‘Bias’, mdl2.LayerBiases{2})];
mdl4 = trainnet(X,Y,layers,’mse’,options);
How is it that trainnet can recognize the solution from fitrnet as optimal, but cannot recreate a similar result using what seems to be identical input parameters? fitrnet, trainnet MATLAB Answers — New Questions
Update the content of a MatLab generated executable
I would like to update the content of an executable inside a generated executable MatLab file. The file is generated with MatLab/Simulink compiler.
Why would I want to do this? Because I need to sign the content of all executable that run on my company pc.
I know I can open the generated executable as a zip file. Inside I can update or add any file.
I have found that there is a sig1.xml file that contains the sha512 encoded with base64. So I have updated the sha512 signature of the modified file. But I have an error when opening the executable: CTF archive is invalid
Is there a global signature to update? Or anything else?
Any advice is welcome!I would like to update the content of an executable inside a generated executable MatLab file. The file is generated with MatLab/Simulink compiler.
Why would I want to do this? Because I need to sign the content of all executable that run on my company pc.
I know I can open the generated executable as a zip file. Inside I can update or add any file.
I have found that there is a sig1.xml file that contains the sha512 encoded with base64. So I have updated the sha512 signature of the modified file. But I have an error when opening the executable: CTF archive is invalid
Is there a global signature to update? Or anything else?
Any advice is welcome! I would like to update the content of an executable inside a generated executable MatLab file. The file is generated with MatLab/Simulink compiler.
Why would I want to do this? Because I need to sign the content of all executable that run on my company pc.
I know I can open the generated executable as a zip file. Inside I can update or add any file.
I have found that there is a sig1.xml file that contains the sha512 encoded with base64. So I have updated the sha512 signature of the modified file. But I have an error when opening the executable: CTF archive is invalid
Is there a global signature to update? Or anything else?
Any advice is welcome! matlab compiler MATLAB Answers — New Questions
Why am I not able to post questions on MATLAB Answers?
Why am I not able to post questions on MATLAB Answers?
When I click “Post Question”, the question is not shared and there is no error message.Why am I not able to post questions on MATLAB Answers?
When I click “Post Question”, the question is not shared and there is no error message. Why am I not able to post questions on MATLAB Answers?
When I click “Post Question”, the question is not shared and there is no error message. MATLAB Answers — New Questions
Exploring DTFT concept using MATLAB
I am trying to understand the concept of DTFT using MATLAB. So I am doing the following experiments:
plot X1[n]=COS(2*pi*201/1024*n) where n=0 to1023
plot X2[n]=rect(N) where N=1024 i.e. X2[n]=1 for n=0 to 1023; else X2[n]=0
plot multiplication of both i.e. X1(n).*X2(n)
plot magnitude plot of Y1(w)=DTFT of { X1(n)*X2(n)} for -pi<w<pi
In figure 7, I expect the peak of sinc function (due to convolution of cosine and rectangular pulse) exactly at the location of the tone freq, but it does not. What may be the issue ???
My code is as below:
clear all; clc; close all;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Nfft = 2^12; % FFT size
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Generate single tone sine wave %%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
tone_num=Nfft/5;
tone_bin = (2*floor(tone_num/2)+1)+0.5; % prime wrt Nfft
n = [0:Nfft-1];
xsin = cos(2*pi*tone_bin/Nfft*n);
%%%%%%%%%%% Plot single tone sine wave %%%%%%%%%%%%%%%%%
figure(1); plot(n,xsin);
%%%%%%%%%%% Plot DTFT of single tone sine wave %%%%%%%%%
[X1 , W1] = dtft ( xsin , Nfft) ;
figure(2);
plot( W1/2/pi , abs (X1) ) ; grid , title( ‘ MAGNITUDE RESPONSE ‘)
xlabel( ‘ NORMALIZED FREQUENCY omega/(2pi)’ ) , ylabel( ‘ I H(omega) I ‘ )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Generate rectangular pulse %%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Nsampl = 200; % number of samples
width=100; % width of the rectangular pulse
sampl_offest=40; % offset from first sampple from where pulse will start
xrect = [zeros(1,sampl_offest) ones(1,width) zeros(1,Nsampl-width-sampl_offest)];
%%%%%%%%%%%%%% PLOT rectangular pulse %%%%%%%%%%%%%%%%%
figure(3);stem(xrect);
%%%%%%%%%%% Plot DTFT of rectangular pulse %%%%%%%%%%%%
[X2 , W2] = dtft ( xrect , Nfft) ;
figure(4);
plot( W2/2/pi , abs (X2) ) ; grid , title( ‘ MAGNITUDE RESPONSE ‘)
xlabel( ‘ NORMALIZED FREQUENCY omega/(2pi)’ ) , ylabel( ‘ I H(omega) I ‘ )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% Generate product of sine & rectangular pulse %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xpdt=xsin(1:Nsampl).*xrect;
%%%%%% Plot product of sine & rectangular pulse %%%%%%%
figure(5); plot(xpdt);
%%% Plot DTFT of product of sine & rectangular pulse %%
[X3 , W3] = dtft ( xpdt , Nfft) ;
figure(6);
plot( W3/2/pi , abs (X3) ) ; grid , title( ‘ MAGNITUDE RESPONSE ‘)
xlabel( ‘ NORMALIZED FREQUENCY omega/(2pi)’ ) , ylabel( ‘ I H(omega) I ‘ )
ylim([-5 max(ylim)+5])
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure(7);
plot( W3/2/pi , abs (X3) ) ; grid , title( ‘ MAGNITUDE RESPONSE ‘)
xlabel( ‘ NORMALIZED FREQUENCY omega/(2pi)’ ) , ylabel( ‘ I H(omega) I ‘ )
k_tone=tone_bin/Nfft; % normalized freq. corresponding to sine tone
xline(k_tone,’:r’,{‘sine tone’}); % plot normalized freq. corresponding to sine tone
wk=1/(Nfft); % freq. bin width
ylim([-5 max(ylim)+5])
xlim([k_tone-30*wk k_tone+30*wk]) % zoom around sine tone freq
%xlim([0 0.5])
%%% generate xticks at every freq. bin w(k) = 2*pi/Nfft %%%%%%%%%%
xwtk=[-0.5 0 0.5];
i=1;
while i*wk < 0.5
xwtk = [xwtk i*wk];
i=i+1;
end
xwtk=sort(xwtk);
xticks(xwtk);
%xline([-k_tone k_tone],’:’,’c’,’sin_tone’);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%% END %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%% DEFINE FUNCTION dtft subroutine %%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [H, W] = dtft(h, N)
%DTFT calculate DTFT at N equally spaced frequencies
%—-
% Usage: [H, W] = dtft(h, N)
%
% h : finite-length input vector, whose length is L
% N : number of frequencies for evaluation over [-pi,pi)
% ==> constraint: N >= L
% H : DTFT values (complex)
% W : (2nd output) vector of freqs where DTFT is computed
%—————————————————————
% copyright 1994, by C.S. Burrus, J.H. McClellan, A.V. Oppenheim,
% T.W. Parks, R.W. Schafer, & H.W. Schussler. For use with the book
% "Computer-Based Exercises for Signal Processing Using MATLAB"
% (Prentice-Hall, 1994).
%—————————————————————
N = fix(N);
L = length(h); h = h(:); %<– for vectors ONLY !!!
if( N < L )
error(‘DTFT: # data samples cannot exceed # freq samples’)
end
W = (2*pi/N) * [ 0:(N-1) ]’;
mid = ceil(N/2) + 1;
W(mid:N) = W(mid:N) – 2*pi; % <— move [pi,2pi) to [-pi,0)
W = fftshift(W);
H = fftshift( fft( h, N ) ); %<— move negative freq components
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%I am trying to understand the concept of DTFT using MATLAB. So I am doing the following experiments:
plot X1[n]=COS(2*pi*201/1024*n) where n=0 to1023
plot X2[n]=rect(N) where N=1024 i.e. X2[n]=1 for n=0 to 1023; else X2[n]=0
plot multiplication of both i.e. X1(n).*X2(n)
plot magnitude plot of Y1(w)=DTFT of { X1(n)*X2(n)} for -pi<w<pi
In figure 7, I expect the peak of sinc function (due to convolution of cosine and rectangular pulse) exactly at the location of the tone freq, but it does not. What may be the issue ???
My code is as below:
clear all; clc; close all;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Nfft = 2^12; % FFT size
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Generate single tone sine wave %%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
tone_num=Nfft/5;
tone_bin = (2*floor(tone_num/2)+1)+0.5; % prime wrt Nfft
n = [0:Nfft-1];
xsin = cos(2*pi*tone_bin/Nfft*n);
%%%%%%%%%%% Plot single tone sine wave %%%%%%%%%%%%%%%%%
figure(1); plot(n,xsin);
%%%%%%%%%%% Plot DTFT of single tone sine wave %%%%%%%%%
[X1 , W1] = dtft ( xsin , Nfft) ;
figure(2);
plot( W1/2/pi , abs (X1) ) ; grid , title( ‘ MAGNITUDE RESPONSE ‘)
xlabel( ‘ NORMALIZED FREQUENCY omega/(2pi)’ ) , ylabel( ‘ I H(omega) I ‘ )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Generate rectangular pulse %%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Nsampl = 200; % number of samples
width=100; % width of the rectangular pulse
sampl_offest=40; % offset from first sampple from where pulse will start
xrect = [zeros(1,sampl_offest) ones(1,width) zeros(1,Nsampl-width-sampl_offest)];
%%%%%%%%%%%%%% PLOT rectangular pulse %%%%%%%%%%%%%%%%%
figure(3);stem(xrect);
%%%%%%%%%%% Plot DTFT of rectangular pulse %%%%%%%%%%%%
[X2 , W2] = dtft ( xrect , Nfft) ;
figure(4);
plot( W2/2/pi , abs (X2) ) ; grid , title( ‘ MAGNITUDE RESPONSE ‘)
xlabel( ‘ NORMALIZED FREQUENCY omega/(2pi)’ ) , ylabel( ‘ I H(omega) I ‘ )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% Generate product of sine & rectangular pulse %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xpdt=xsin(1:Nsampl).*xrect;
%%%%%% Plot product of sine & rectangular pulse %%%%%%%
figure(5); plot(xpdt);
%%% Plot DTFT of product of sine & rectangular pulse %%
[X3 , W3] = dtft ( xpdt , Nfft) ;
figure(6);
plot( W3/2/pi , abs (X3) ) ; grid , title( ‘ MAGNITUDE RESPONSE ‘)
xlabel( ‘ NORMALIZED FREQUENCY omega/(2pi)’ ) , ylabel( ‘ I H(omega) I ‘ )
ylim([-5 max(ylim)+5])
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure(7);
plot( W3/2/pi , abs (X3) ) ; grid , title( ‘ MAGNITUDE RESPONSE ‘)
xlabel( ‘ NORMALIZED FREQUENCY omega/(2pi)’ ) , ylabel( ‘ I H(omega) I ‘ )
k_tone=tone_bin/Nfft; % normalized freq. corresponding to sine tone
xline(k_tone,’:r’,{‘sine tone’}); % plot normalized freq. corresponding to sine tone
wk=1/(Nfft); % freq. bin width
ylim([-5 max(ylim)+5])
xlim([k_tone-30*wk k_tone+30*wk]) % zoom around sine tone freq
%xlim([0 0.5])
%%% generate xticks at every freq. bin w(k) = 2*pi/Nfft %%%%%%%%%%
xwtk=[-0.5 0 0.5];
i=1;
while i*wk < 0.5
xwtk = [xwtk i*wk];
i=i+1;
end
xwtk=sort(xwtk);
xticks(xwtk);
%xline([-k_tone k_tone],’:’,’c’,’sin_tone’);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%% END %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%% DEFINE FUNCTION dtft subroutine %%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [H, W] = dtft(h, N)
%DTFT calculate DTFT at N equally spaced frequencies
%—-
% Usage: [H, W] = dtft(h, N)
%
% h : finite-length input vector, whose length is L
% N : number of frequencies for evaluation over [-pi,pi)
% ==> constraint: N >= L
% H : DTFT values (complex)
% W : (2nd output) vector of freqs where DTFT is computed
%—————————————————————
% copyright 1994, by C.S. Burrus, J.H. McClellan, A.V. Oppenheim,
% T.W. Parks, R.W. Schafer, & H.W. Schussler. For use with the book
% "Computer-Based Exercises for Signal Processing Using MATLAB"
% (Prentice-Hall, 1994).
%—————————————————————
N = fix(N);
L = length(h); h = h(:); %<– for vectors ONLY !!!
if( N < L )
error(‘DTFT: # data samples cannot exceed # freq samples’)
end
W = (2*pi/N) * [ 0:(N-1) ]’;
mid = ceil(N/2) + 1;
W(mid:N) = W(mid:N) – 2*pi; % <— move [pi,2pi) to [-pi,0)
W = fftshift(W);
H = fftshift( fft( h, N ) ); %<— move negative freq components
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% I am trying to understand the concept of DTFT using MATLAB. So I am doing the following experiments:
plot X1[n]=COS(2*pi*201/1024*n) where n=0 to1023
plot X2[n]=rect(N) where N=1024 i.e. X2[n]=1 for n=0 to 1023; else X2[n]=0
plot multiplication of both i.e. X1(n).*X2(n)
plot magnitude plot of Y1(w)=DTFT of { X1(n)*X2(n)} for -pi<w<pi
In figure 7, I expect the peak of sinc function (due to convolution of cosine and rectangular pulse) exactly at the location of the tone freq, but it does not. What may be the issue ???
My code is as below:
clear all; clc; close all;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Nfft = 2^12; % FFT size
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Generate single tone sine wave %%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
tone_num=Nfft/5;
tone_bin = (2*floor(tone_num/2)+1)+0.5; % prime wrt Nfft
n = [0:Nfft-1];
xsin = cos(2*pi*tone_bin/Nfft*n);
%%%%%%%%%%% Plot single tone sine wave %%%%%%%%%%%%%%%%%
figure(1); plot(n,xsin);
%%%%%%%%%%% Plot DTFT of single tone sine wave %%%%%%%%%
[X1 , W1] = dtft ( xsin , Nfft) ;
figure(2);
plot( W1/2/pi , abs (X1) ) ; grid , title( ‘ MAGNITUDE RESPONSE ‘)
xlabel( ‘ NORMALIZED FREQUENCY omega/(2pi)’ ) , ylabel( ‘ I H(omega) I ‘ )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%% Generate rectangular pulse %%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Nsampl = 200; % number of samples
width=100; % width of the rectangular pulse
sampl_offest=40; % offset from first sampple from where pulse will start
xrect = [zeros(1,sampl_offest) ones(1,width) zeros(1,Nsampl-width-sampl_offest)];
%%%%%%%%%%%%%% PLOT rectangular pulse %%%%%%%%%%%%%%%%%
figure(3);stem(xrect);
%%%%%%%%%%% Plot DTFT of rectangular pulse %%%%%%%%%%%%
[X2 , W2] = dtft ( xrect , Nfft) ;
figure(4);
plot( W2/2/pi , abs (X2) ) ; grid , title( ‘ MAGNITUDE RESPONSE ‘)
xlabel( ‘ NORMALIZED FREQUENCY omega/(2pi)’ ) , ylabel( ‘ I H(omega) I ‘ )
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% Generate product of sine & rectangular pulse %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
xpdt=xsin(1:Nsampl).*xrect;
%%%%%% Plot product of sine & rectangular pulse %%%%%%%
figure(5); plot(xpdt);
%%% Plot DTFT of product of sine & rectangular pulse %%
[X3 , W3] = dtft ( xpdt , Nfft) ;
figure(6);
plot( W3/2/pi , abs (X3) ) ; grid , title( ‘ MAGNITUDE RESPONSE ‘)
xlabel( ‘ NORMALIZED FREQUENCY omega/(2pi)’ ) , ylabel( ‘ I H(omega) I ‘ )
ylim([-5 max(ylim)+5])
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure(7);
plot( W3/2/pi , abs (X3) ) ; grid , title( ‘ MAGNITUDE RESPONSE ‘)
xlabel( ‘ NORMALIZED FREQUENCY omega/(2pi)’ ) , ylabel( ‘ I H(omega) I ‘ )
k_tone=tone_bin/Nfft; % normalized freq. corresponding to sine tone
xline(k_tone,’:r’,{‘sine tone’}); % plot normalized freq. corresponding to sine tone
wk=1/(Nfft); % freq. bin width
ylim([-5 max(ylim)+5])
xlim([k_tone-30*wk k_tone+30*wk]) % zoom around sine tone freq
%xlim([0 0.5])
%%% generate xticks at every freq. bin w(k) = 2*pi/Nfft %%%%%%%%%%
xwtk=[-0.5 0 0.5];
i=1;
while i*wk < 0.5
xwtk = [xwtk i*wk];
i=i+1;
end
xwtk=sort(xwtk);
xticks(xwtk);
%xline([-k_tone k_tone],’:’,’c’,’sin_tone’);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%% END %%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%% DEFINE FUNCTION dtft subroutine %%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [H, W] = dtft(h, N)
%DTFT calculate DTFT at N equally spaced frequencies
%—-
% Usage: [H, W] = dtft(h, N)
%
% h : finite-length input vector, whose length is L
% N : number of frequencies for evaluation over [-pi,pi)
% ==> constraint: N >= L
% H : DTFT values (complex)
% W : (2nd output) vector of freqs where DTFT is computed
%—————————————————————
% copyright 1994, by C.S. Burrus, J.H. McClellan, A.V. Oppenheim,
% T.W. Parks, R.W. Schafer, & H.W. Schussler. For use with the book
% "Computer-Based Exercises for Signal Processing Using MATLAB"
% (Prentice-Hall, 1994).
%—————————————————————
N = fix(N);
L = length(h); h = h(:); %<– for vectors ONLY !!!
if( N < L )
error(‘DTFT: # data samples cannot exceed # freq samples’)
end
W = (2*pi/N) * [ 0:(N-1) ]’;
mid = ceil(N/2) + 1;
W(mid:N) = W(mid:N) – 2*pi; % <— move [pi,2pi) to [-pi,0)
W = fftshift(W);
H = fftshift( fft( h, N ) ); %<— move negative freq components
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% dtft, dft, matlab, fft MATLAB Answers — New Questions
Error in example comm/DecisionFeedbackEqualizeBPSKModulatedSignalExample
In the example comm/DecisionFeedbackEqualizeBPSKModulatedSignalExample the following line:
eqdfe_lms = comm.DecisionFeedbackEqualizer(‘Algorithm’,’LMS’, …
‘NumForwardTaps’,8,’NumFeedbackTaps’,5,’StepSize’,0.03);
Needs to read:
eqdfe_lms = comm.DecisionFeedbackEqualizer(‘Algorithm’,’LMS’, …
‘NumForwardTaps’,8,’NumFeedbackTaps’,5,’StepSize’,0.03, …
‘Constellation’, pskmod(0:1, 2));
This is because the default for comm.DecisionFeedbackEqualizer seems to be QPSK not BPSK.
Also the line above it:
bpsk = comm.BPSKModulator;
Is deprecated, it can be changed to:
bpsk = @(x) pskmod(x, 2);In the example comm/DecisionFeedbackEqualizeBPSKModulatedSignalExample the following line:
eqdfe_lms = comm.DecisionFeedbackEqualizer(‘Algorithm’,’LMS’, …
‘NumForwardTaps’,8,’NumFeedbackTaps’,5,’StepSize’,0.03);
Needs to read:
eqdfe_lms = comm.DecisionFeedbackEqualizer(‘Algorithm’,’LMS’, …
‘NumForwardTaps’,8,’NumFeedbackTaps’,5,’StepSize’,0.03, …
‘Constellation’, pskmod(0:1, 2));
This is because the default for comm.DecisionFeedbackEqualizer seems to be QPSK not BPSK.
Also the line above it:
bpsk = comm.BPSKModulator;
Is deprecated, it can be changed to:
bpsk = @(x) pskmod(x, 2); In the example comm/DecisionFeedbackEqualizeBPSKModulatedSignalExample the following line:
eqdfe_lms = comm.DecisionFeedbackEqualizer(‘Algorithm’,’LMS’, …
‘NumForwardTaps’,8,’NumFeedbackTaps’,5,’StepSize’,0.03);
Needs to read:
eqdfe_lms = comm.DecisionFeedbackEqualizer(‘Algorithm’,’LMS’, …
‘NumForwardTaps’,8,’NumFeedbackTaps’,5,’StepSize’,0.03, …
‘Constellation’, pskmod(0:1, 2));
This is because the default for comm.DecisionFeedbackEqualizer seems to be QPSK not BPSK.
Also the line above it:
bpsk = comm.BPSKModulator;
Is deprecated, it can be changed to:
bpsk = @(x) pskmod(x, 2); communication MATLAB Answers — New Questions
Why does my ISO roads doesn´t fit to the reference values ?
Hello everybody !
I was generating random road profiles according to the ISO 8608 standard with the help of the following article:
http://link.springer.com/article/10.1007%2Fs12544-013-0127-8/fulltext.html
To prove if my roads have the given PSD-Value (for example Gd_0 = 16 * (10^-6) Road A), i used the 1D PSD function and generated a plot with PSD road displacement and ISO PSD over the spatial frequency.
1D PSD calculation for surface roughness profiles
My problem is that the PSD values does not fit together. If i´m generating a road with 16 * (10^-6), the graph should be in the middle of the reference ISO line.
Has anyone the same problem and can help ?
Many thanks !
Here my code:
clear all;close all;
% spatial frequency (n0) cycles per meter
Omega0 = 0.1;
% psd ISO (used for formula 8)
Gd_0 = 16 * (10^-6);
% waveviness
w = 2;
% road length
L = 250;
%delta n
N = 1000;
Omega_L = 0.004;
Omega_U = 4;
delta_n = 1/L; % delta_n = (Omega_U – Omega_L)/(N-1);
% spatial frequency band
Omega = Omega_L:delta_n:Omega_U;
%PSD of road
Gd = Gd_0.*(Omega./Omega0).^(-w);
% calculate amplitude using formula(8)
Amp = sqrt(2*Gd*delta_n);
% calculate amplitude using simplified formula(9)
% k = 3;
% Amp = sqrt(delta_n) * (2^k) * (10^-3) * (Omega0./Omega);
%random phases
Psi = 2*pi*rand(size(Omega));
% x abicsa from 0 to L
x = 0:0.25:250;
% road sinal
h= zeros(size(x));
for i=1:length(x)
h(i) = sum( Amp.*cos(2*pi*Omega*x(i) + Psi) );
end
plot(x, h*1000 );
xlabel(‘Distance m’);
ylabel(‘Elevation (mm)’);
grid on
%————————————————————————-
B = L/N;
[q , C] = psd_1D(h, B, ‘x’) % B is Sampling Interval (m)
lambda = (2*pi) ./ q; % wavelengths
f = q / (2*pi); % spatial frequency
PSD = 2 * pi * C; % power spectrum
figure(2)
loglog(f,PSD,Omega,Gd)
legend(‘PSD ISO Road’, ‘Reference PSD’)
xlabel(‘spatial frequency [cycle/m]’)
ylabel(‘PSD [m^3]’)
grid onHello everybody !
I was generating random road profiles according to the ISO 8608 standard with the help of the following article:
http://link.springer.com/article/10.1007%2Fs12544-013-0127-8/fulltext.html
To prove if my roads have the given PSD-Value (for example Gd_0 = 16 * (10^-6) Road A), i used the 1D PSD function and generated a plot with PSD road displacement and ISO PSD over the spatial frequency.
1D PSD calculation for surface roughness profiles
My problem is that the PSD values does not fit together. If i´m generating a road with 16 * (10^-6), the graph should be in the middle of the reference ISO line.
Has anyone the same problem and can help ?
Many thanks !
Here my code:
clear all;close all;
% spatial frequency (n0) cycles per meter
Omega0 = 0.1;
% psd ISO (used for formula 8)
Gd_0 = 16 * (10^-6);
% waveviness
w = 2;
% road length
L = 250;
%delta n
N = 1000;
Omega_L = 0.004;
Omega_U = 4;
delta_n = 1/L; % delta_n = (Omega_U – Omega_L)/(N-1);
% spatial frequency band
Omega = Omega_L:delta_n:Omega_U;
%PSD of road
Gd = Gd_0.*(Omega./Omega0).^(-w);
% calculate amplitude using formula(8)
Amp = sqrt(2*Gd*delta_n);
% calculate amplitude using simplified formula(9)
% k = 3;
% Amp = sqrt(delta_n) * (2^k) * (10^-3) * (Omega0./Omega);
%random phases
Psi = 2*pi*rand(size(Omega));
% x abicsa from 0 to L
x = 0:0.25:250;
% road sinal
h= zeros(size(x));
for i=1:length(x)
h(i) = sum( Amp.*cos(2*pi*Omega*x(i) + Psi) );
end
plot(x, h*1000 );
xlabel(‘Distance m’);
ylabel(‘Elevation (mm)’);
grid on
%————————————————————————-
B = L/N;
[q , C] = psd_1D(h, B, ‘x’) % B is Sampling Interval (m)
lambda = (2*pi) ./ q; % wavelengths
f = q / (2*pi); % spatial frequency
PSD = 2 * pi * C; % power spectrum
figure(2)
loglog(f,PSD,Omega,Gd)
legend(‘PSD ISO Road’, ‘Reference PSD’)
xlabel(‘spatial frequency [cycle/m]’)
ylabel(‘PSD [m^3]’)
grid on Hello everybody !
I was generating random road profiles according to the ISO 8608 standard with the help of the following article:
http://link.springer.com/article/10.1007%2Fs12544-013-0127-8/fulltext.html
To prove if my roads have the given PSD-Value (for example Gd_0 = 16 * (10^-6) Road A), i used the 1D PSD function and generated a plot with PSD road displacement and ISO PSD over the spatial frequency.
1D PSD calculation for surface roughness profiles
My problem is that the PSD values does not fit together. If i´m generating a road with 16 * (10^-6), the graph should be in the middle of the reference ISO line.
Has anyone the same problem and can help ?
Many thanks !
Here my code:
clear all;close all;
% spatial frequency (n0) cycles per meter
Omega0 = 0.1;
% psd ISO (used for formula 8)
Gd_0 = 16 * (10^-6);
% waveviness
w = 2;
% road length
L = 250;
%delta n
N = 1000;
Omega_L = 0.004;
Omega_U = 4;
delta_n = 1/L; % delta_n = (Omega_U – Omega_L)/(N-1);
% spatial frequency band
Omega = Omega_L:delta_n:Omega_U;
%PSD of road
Gd = Gd_0.*(Omega./Omega0).^(-w);
% calculate amplitude using formula(8)
Amp = sqrt(2*Gd*delta_n);
% calculate amplitude using simplified formula(9)
% k = 3;
% Amp = sqrt(delta_n) * (2^k) * (10^-3) * (Omega0./Omega);
%random phases
Psi = 2*pi*rand(size(Omega));
% x abicsa from 0 to L
x = 0:0.25:250;
% road sinal
h= zeros(size(x));
for i=1:length(x)
h(i) = sum( Amp.*cos(2*pi*Omega*x(i) + Psi) );
end
plot(x, h*1000 );
xlabel(‘Distance m’);
ylabel(‘Elevation (mm)’);
grid on
%————————————————————————-
B = L/N;
[q , C] = psd_1D(h, B, ‘x’) % B is Sampling Interval (m)
lambda = (2*pi) ./ q; % wavelengths
f = q / (2*pi); % spatial frequency
PSD = 2 * pi * C; % power spectrum
figure(2)
loglog(f,PSD,Omega,Gd)
legend(‘PSD ISO Road’, ‘Reference PSD’)
xlabel(‘spatial frequency [cycle/m]’)
ylabel(‘PSD [m^3]’)
grid on iso road 8608, random, road, psd, matlab, 8608, 1d psd MATLAB Answers — New Questions
Open/Edit docs stored on Microsoft Teams
I am trying to use matlab (2024a) to open (and eventually edit) an excel doc that is stored in Microsoft teams. I am getting a 403 Forbidden response. Our IT department is stumped, as I am entering the correct credentials when prompted. Anyone been able to get around this?
Here is my code:
% Prompt for username and password
prompt = {‘Enter your username:’, ‘Enter your password:’};
dlgtitle = ‘SharePoint Login’;
dims = [1 35];
definput = {”, ”};
answer = inputdlg(prompt, dlgtitle, dims, definput);
% Extract username and password
username = answer{1};
password = answer{2};
% URL for the SharePoint file
url = ‘https://indiana.sharepoint.com/sites/msteams_c777c3-DistVRT/_api/web/GetFileByServerRelativeUrl(”/sites/msteams_c777c3-DistVRT/Shared%20Documents/DistVRT/DistVRT_v4_SF_DataScoringLog.xlsx”)/$value’;
% Web options with the provided credentials
options = weboptions(‘Username’, username, ‘Password’, password, ‘Timeout’, 60);
% Read the file from SharePoint
data = webread(url, options);
data = readtable(‘https://indiana.sharepoint.com/sites/msteams_c777c3-DistVRT/Shared%20Documents/DistVRT/DistVRT_v4_SF_DataScoringLog.xlsx’,’ReadVariableNames’,1); %calls in text file of data for this subjectI am trying to use matlab (2024a) to open (and eventually edit) an excel doc that is stored in Microsoft teams. I am getting a 403 Forbidden response. Our IT department is stumped, as I am entering the correct credentials when prompted. Anyone been able to get around this?
Here is my code:
% Prompt for username and password
prompt = {‘Enter your username:’, ‘Enter your password:’};
dlgtitle = ‘SharePoint Login’;
dims = [1 35];
definput = {”, ”};
answer = inputdlg(prompt, dlgtitle, dims, definput);
% Extract username and password
username = answer{1};
password = answer{2};
% URL for the SharePoint file
url = ‘https://indiana.sharepoint.com/sites/msteams_c777c3-DistVRT/_api/web/GetFileByServerRelativeUrl(”/sites/msteams_c777c3-DistVRT/Shared%20Documents/DistVRT/DistVRT_v4_SF_DataScoringLog.xlsx”)/$value’;
% Web options with the provided credentials
options = weboptions(‘Username’, username, ‘Password’, password, ‘Timeout’, 60);
% Read the file from SharePoint
data = webread(url, options);
data = readtable(‘https://indiana.sharepoint.com/sites/msteams_c777c3-DistVRT/Shared%20Documents/DistVRT/DistVRT_v4_SF_DataScoringLog.xlsx’,’ReadVariableNames’,1); %calls in text file of data for this subject I am trying to use matlab (2024a) to open (and eventually edit) an excel doc that is stored in Microsoft teams. I am getting a 403 Forbidden response. Our IT department is stumped, as I am entering the correct credentials when prompted. Anyone been able to get around this?
Here is my code:
% Prompt for username and password
prompt = {‘Enter your username:’, ‘Enter your password:’};
dlgtitle = ‘SharePoint Login’;
dims = [1 35];
definput = {”, ”};
answer = inputdlg(prompt, dlgtitle, dims, definput);
% Extract username and password
username = answer{1};
password = answer{2};
% URL for the SharePoint file
url = ‘https://indiana.sharepoint.com/sites/msteams_c777c3-DistVRT/_api/web/GetFileByServerRelativeUrl(”/sites/msteams_c777c3-DistVRT/Shared%20Documents/DistVRT/DistVRT_v4_SF_DataScoringLog.xlsx”)/$value’;
% Web options with the provided credentials
options = weboptions(‘Username’, username, ‘Password’, password, ‘Timeout’, 60);
% Read the file from SharePoint
data = webread(url, options);
data = readtable(‘https://indiana.sharepoint.com/sites/msteams_c777c3-DistVRT/Shared%20Documents/DistVRT/DistVRT_v4_SF_DataScoringLog.xlsx’,’ReadVariableNames’,1); %calls in text file of data for this subject importing excel data, microsoft teams, permissions MATLAB Answers — New Questions
How can I get a .mltbx package to display a license dialog?
I have been trying to create a toolbox install file (.mltbx) using the "Package Toolbox" app. I would like to implement what I’ve seen some packages on File Central do: Display a license page, and wait for the user to accept it before proceeding with the install. I tried to place files with names "license.txt", "license.html", "license.xml" and "license" in the root folder to no avail. Root folder structure is like this:
root
myToolbox
file1.m
file2.m
myToolboxDocs
html
file1.html
file2.html
index.html
helptoc.xml
info.xml
license.txt
license.html
license.xml
license.
The generated .mltbx file installs fine, but does not display a license dialog. Dissecting a downloaded package that is able to display a license dialog (I have unzipped it) I can see that the "manifest" folder has a file named "license.xml" that my generated .mltbx file does not have. I must be missing something here, but I cannot figure out what. Any ideas?I have been trying to create a toolbox install file (.mltbx) using the "Package Toolbox" app. I would like to implement what I’ve seen some packages on File Central do: Display a license page, and wait for the user to accept it before proceeding with the install. I tried to place files with names "license.txt", "license.html", "license.xml" and "license" in the root folder to no avail. Root folder structure is like this:
root
myToolbox
file1.m
file2.m
myToolboxDocs
html
file1.html
file2.html
index.html
helptoc.xml
info.xml
license.txt
license.html
license.xml
license.
The generated .mltbx file installs fine, but does not display a license dialog. Dissecting a downloaded package that is able to display a license dialog (I have unzipped it) I can see that the "manifest" folder has a file named "license.xml" that my generated .mltbx file does not have. I must be missing something here, but I cannot figure out what. Any ideas? I have been trying to create a toolbox install file (.mltbx) using the "Package Toolbox" app. I would like to implement what I’ve seen some packages on File Central do: Display a license page, and wait for the user to accept it before proceeding with the install. I tried to place files with names "license.txt", "license.html", "license.xml" and "license" in the root folder to no avail. Root folder structure is like this:
root
myToolbox
file1.m
file2.m
myToolboxDocs
html
file1.html
file2.html
index.html
helptoc.xml
info.xml
license.txt
license.html
license.xml
license.
The generated .mltbx file installs fine, but does not display a license dialog. Dissecting a downloaded package that is able to display a license dialog (I have unzipped it) I can see that the "manifest" folder has a file named "license.xml" that my generated .mltbx file does not have. I must be missing something here, but I cannot figure out what. Any ideas? package toolbox, matlab MATLAB Answers — New Questions
צריך לחשב את האינטגרל
צריך לחשב את האינטגרל הבאצריך לחשב את האינטגרל הבא צריך לחשב את האינטגרל הבא השאלה בקורס אינפי ג MATLAB Answers — New Questions
Optimal placement and sizing of shunt capacitor in power systems using MATLAB and genetic algorithm
I am writing to request your guidance on developing a MATLAB code for optimal placement and sizing of four capacitors in the standard IEEE 33-bus system to minimize network losses.
Thanks in advanced.I am writing to request your guidance on developing a MATLAB code for optimal placement and sizing of four capacitors in the standard IEEE 33-bus system to minimize network losses.
Thanks in advanced. I am writing to request your guidance on developing a MATLAB code for optimal placement and sizing of four capacitors in the standard IEEE 33-bus system to minimize network losses.
Thanks in advanced. genetic algorithm, optimal placement and sizing MATLAB Answers — New Questions
Simulation of a Fuel Cell Hybrid Vehicle ( Fuel Cell + Battery only )
Hi folks,
Can any one help me in buiding the model of Fuel Cell Hybrid Vehicle. One model is already here but not running on version R2024b. Error message is regarding missing libraries. The exact errors are mentioned below:
Error in ‘power_FCV_powertrain/Energy Management Subsystem’: Failed to evaluate mask initialization commands.
Caused by:
Unrecognized function or variable ‘spsdrivelogo’.
Variable ‘spsdrivelogo’ does not exist.
Suggested Actions
Load a file into base workspace.
Fix
Create a new variable.
Fix
Component:Simulink | Category:Model error
Failed to load library ‘DC6DriveInternalModels’ referenced by ‘power_FCV_powertrain/FCV Electrical Subsystem/DC-DC converter/DC//DC converter/Chopper’.
Component:Simulink | Category:Model error
Error in ‘power_FCV_powertrain/FCV Electrical Subsystem/PM Synchronous Motor Drive This block is based on the AC6 drive block/Speed Controller’: Failed to evaluate mask initialization commands.
Caused by:
Unrecognized function or variable ‘spsdrivelogo’.
Variable ‘spsdrivelogo’ does not exist.
Suggested Actions
Load a file into base workspace.
Fix
Create a new variable.
Fix
Component:Simulink | Category:Model error
Error in ‘power_FCV_powertrain/FCV Electrical Subsystem/PM Synchronous Motor Drive This block is based on the AC6 drive block/VECT’: Failed to evaluate mask initialization commands.
Caused by:
Unrecognized function or variable ‘spsdrivelogo’.
Variable ‘spsdrivelogo’ does not exist.
Suggested Actions
Load a file into base workspace.
Fix
Create a new variable.
Fix
Component:Simulink | Category:Model error
Failed to load library ‘AC6DriveInternalModels’ referenced by ‘power_FCV_powertrain/FCV Electrical Subsystem/PM Synchronous Motor Drive This block is based on the AC6 drive block/VECT/Current Regulator’.
Component:Simulink | Category:Model error
Kindly revert.
Regards, Bhasker SharmaHi folks,
Can any one help me in buiding the model of Fuel Cell Hybrid Vehicle. One model is already here but not running on version R2024b. Error message is regarding missing libraries. The exact errors are mentioned below:
Error in ‘power_FCV_powertrain/Energy Management Subsystem’: Failed to evaluate mask initialization commands.
Caused by:
Unrecognized function or variable ‘spsdrivelogo’.
Variable ‘spsdrivelogo’ does not exist.
Suggested Actions
Load a file into base workspace.
Fix
Create a new variable.
Fix
Component:Simulink | Category:Model error
Failed to load library ‘DC6DriveInternalModels’ referenced by ‘power_FCV_powertrain/FCV Electrical Subsystem/DC-DC converter/DC//DC converter/Chopper’.
Component:Simulink | Category:Model error
Error in ‘power_FCV_powertrain/FCV Electrical Subsystem/PM Synchronous Motor Drive This block is based on the AC6 drive block/Speed Controller’: Failed to evaluate mask initialization commands.
Caused by:
Unrecognized function or variable ‘spsdrivelogo’.
Variable ‘spsdrivelogo’ does not exist.
Suggested Actions
Load a file into base workspace.
Fix
Create a new variable.
Fix
Component:Simulink | Category:Model error
Error in ‘power_FCV_powertrain/FCV Electrical Subsystem/PM Synchronous Motor Drive This block is based on the AC6 drive block/VECT’: Failed to evaluate mask initialization commands.
Caused by:
Unrecognized function or variable ‘spsdrivelogo’.
Variable ‘spsdrivelogo’ does not exist.
Suggested Actions
Load a file into base workspace.
Fix
Create a new variable.
Fix
Component:Simulink | Category:Model error
Failed to load library ‘AC6DriveInternalModels’ referenced by ‘power_FCV_powertrain/FCV Electrical Subsystem/PM Synchronous Motor Drive This block is based on the AC6 drive block/VECT/Current Regulator’.
Component:Simulink | Category:Model error
Kindly revert.
Regards, Bhasker Sharma Hi folks,
Can any one help me in buiding the model of Fuel Cell Hybrid Vehicle. One model is already here but not running on version R2024b. Error message is regarding missing libraries. The exact errors are mentioned below:
Error in ‘power_FCV_powertrain/Energy Management Subsystem’: Failed to evaluate mask initialization commands.
Caused by:
Unrecognized function or variable ‘spsdrivelogo’.
Variable ‘spsdrivelogo’ does not exist.
Suggested Actions
Load a file into base workspace.
Fix
Create a new variable.
Fix
Component:Simulink | Category:Model error
Failed to load library ‘DC6DriveInternalModels’ referenced by ‘power_FCV_powertrain/FCV Electrical Subsystem/DC-DC converter/DC//DC converter/Chopper’.
Component:Simulink | Category:Model error
Error in ‘power_FCV_powertrain/FCV Electrical Subsystem/PM Synchronous Motor Drive This block is based on the AC6 drive block/Speed Controller’: Failed to evaluate mask initialization commands.
Caused by:
Unrecognized function or variable ‘spsdrivelogo’.
Variable ‘spsdrivelogo’ does not exist.
Suggested Actions
Load a file into base workspace.
Fix
Create a new variable.
Fix
Component:Simulink | Category:Model error
Error in ‘power_FCV_powertrain/FCV Electrical Subsystem/PM Synchronous Motor Drive This block is based on the AC6 drive block/VECT’: Failed to evaluate mask initialization commands.
Caused by:
Unrecognized function or variable ‘spsdrivelogo’.
Variable ‘spsdrivelogo’ does not exist.
Suggested Actions
Load a file into base workspace.
Fix
Create a new variable.
Fix
Component:Simulink | Category:Model error
Failed to load library ‘AC6DriveInternalModels’ referenced by ‘power_FCV_powertrain/FCV Electrical Subsystem/PM Synchronous Motor Drive This block is based on the AC6 drive block/VECT/Current Regulator’.
Component:Simulink | Category:Model error
Kindly revert.
Regards, Bhasker Sharma transferred MATLAB Answers — New Questions
changing rmw of the auto-generated ros2 node leads to increased CPU consumption
Hello, I run a node on Ubuntu 20.04 (ros2 humble) with a standard rmw (fastrtps), look in htop and see 10-15% CPU load by my node, stop the node, change the rmw on cyclondds, start it and see the CPU load 35-40%…I tried to rebuild the node with the selected cyclondds in the Matlab ros settings – it didn’t help
Can someone explain how to fix it?Hello, I run a node on Ubuntu 20.04 (ros2 humble) with a standard rmw (fastrtps), look in htop and see 10-15% CPU load by my node, stop the node, change the rmw on cyclondds, start it and see the CPU load 35-40%…I tried to rebuild the node with the selected cyclondds in the Matlab ros settings – it didn’t help
Can someone explain how to fix it? Hello, I run a node on Ubuntu 20.04 (ros2 humble) with a standard rmw (fastrtps), look in htop and see 10-15% CPU load by my node, stop the node, change the rmw on cyclondds, start it and see the CPU load 35-40%…I tried to rebuild the node with the selected cyclondds in the Matlab ros settings – it didn’t help
Can someone explain how to fix it? ros2, rmw MATLAB Answers — New Questions
how to import csv file in matlab
Hi, I have one question. I need to import data into MATLAB from a CSV file. Unfortunately, the data has header information in 3 columns. How do I skip the headers and get the data directly? For example: a= import data (‘C:s11.dat’) * Then what is the next step? I need your help. Thank you.Hi, I have one question. I need to import data into MATLAB from a CSV file. Unfortunately, the data has header information in 3 columns. How do I skip the headers and get the data directly? For example: a= import data (‘C:s11.dat’) * Then what is the next step? I need your help. Thank you. Hi, I have one question. I need to import data into MATLAB from a CSV file. Unfortunately, the data has header information in 3 columns. How do I skip the headers and get the data directly? For example: a= import data (‘C:s11.dat’) * Then what is the next step? I need your help. Thank you. MATLAB Answers — New Questions
Varying over the horizon constraint on linear combination of inputs for linear MPC
I am designing a constrained linear MPC. I would like to introduce a constraint on a linear combination of inputs which changes over the prediction horizon. Does MATLAB support this kind of constraints?
Thank you!I am designing a constrained linear MPC. I would like to introduce a constraint on a linear combination of inputs which changes over the prediction horizon. Does MATLAB support this kind of constraints?
Thank you! I am designing a constrained linear MPC. I would like to introduce a constraint on a linear combination of inputs which changes over the prediction horizon. Does MATLAB support this kind of constraints?
Thank you! linear mpc, constraint on linear combination of inputs MATLAB Answers — New Questions