필터 지우기
필터 지우기

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

조회 수: 2 (최근 30일)
Giuseppe
Giuseppe 2018년 7월 21일
댓글: Giuseppe 2018년 7월 26일
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