Inside -for loop- store a single value and a matrix. How to?
3 views (last 30 days)
Show older comments
Hello guys,
I have a specific code issue. My raw data (x) is a matrix where each column is a measurement (trial 1, trial2, etc.).
Problem: I created a -for loop- portion in the code below. I need to record the NCP outcome (thus a matrix containing the NCP for each iteration resulting in a matrix of n columns as many as the raw data) and the Fc variable for each iteration. Otherwise the previous value/matrix is ovewritten and I will get only the last calculation. I think for the Fc(x) works (I get a row vector with as many columns as the number of iterations) but I can't get this done for the NCP matrix.
Any help would help me to fix the problems, and to better understand how matlab works. Thank you
x=data; %give to x the name of the raw data variable in the workspace
ncol = size(x,2);
Fs=1000; NFFT=4096;
for k = 1:ncol
%--------------------------------------------
L=length(x(:,k));
X=fftshift(fft(x(:,k),NFFT));
Px=X.*conj(X)/(NFFT*L); %Power of each freq components
fVals=Fs*(-NFFT/2:NFFT/2-1)/NFFT;
fVals=fVals((NFFT/2+1):end);
Px=Px((NFFT/2+1):end);
CP = cumsum(Px) ;
NCP = CP / CP(end)*100;
figure1 = figure('Color',[1 1 1]);
axes1 = axes('Parent',figure1,'FontSize',14);
box(axes1,'on');
hold(axes1,'all');
plot(fVals,NCP,'MarkerSize',1,'LineWidth',2,'Color',[0 0 0]);
title('Cumulative Power');
xlabel('Frequency (Hz)','LineWidth',1,'FontWeight','bold','FontSize',14);
ylabel('Power (%)','FontWeight','bold','FontSize',14);
optimal_Fc=find(NCP>99);
Fc(k)=fVals(1,(optimal_Fc(1))); %76.179Hz
end
0 Comments
Accepted Answer
Adam Danz
on 23 Jul 2018
Edited: Adam Danz
on 23 Jul 2018
You correctly stored single values in Fc(k) which becomes a vector. When you store vectors such as NCP, they will become matrices. Matrices become 3D arrays and so on (always adding a dimension).
change
NCP = CP / CP(end)*100;
to
NCP(:,k) = CP / CP(end)*100;
Also, prior to your loop, allocate the arrays.
NCP = nan(q, ncol); %where q is the length of each vector - you can figure that one out.
Fc = nan(1, ncol);
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!