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

1 vue (au cours des 30 derniers jours)
Giuseppe
Giuseppe le 21 Juil 2018
Commenté : Giuseppe le 26 Juil 2018
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

Réponse acceptée

Adam Danz
Adam Danz le 23 Juil 2018
Modifié(e) : Adam Danz le 23 Juil 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);
  1 commentaire
Giuseppe
Giuseppe le 26 Juil 2018
Thanks Adam, tha was very helpful. The code works and the problem is fixed. q was basically NFFT/2 in that specific case. Cheers

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Produits


Version

R2014a

Community Treasure Hunt

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

Start Hunting!

Translated by