Inside -for loop- store a single value and a matrix. How to?

1 次查看(过去 30 天)
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

采纳的回答

Adam Danz
Adam Danz 2018-7-23
编辑:Adam Danz 2018-7-23
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);
  1 个评论
Giuseppe
Giuseppe 2018-7-26
Thanks Adam, tha was very helpful. The code works and the problem is fixed. q was basically NFFT/2 in that specific case. Cheers

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2014a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by