if loop within for loop for statistical analysis of data
Show older comments
Hi,
I am having a code with data, that consists of a very large column vector in the form of:
P_b=[2;3;4;5;6;NaN;3;4;5;6;NaN;3;4;2;NaN;3;Nan];
For that vector, I would like to group all consecutive non-NaN values, i.e. [2;3;4;5;6],[3;4;5;6] etc. fit a normal distribution to them, extract the mean, and have the result come up in a vector. This vector includes all the means of the 'grouped' data of P_b.
May sound kind of complicated but it shouldn't be. I have created the code below, however an odd problem that arrises is that MATLAB does not recognise the variable 'avg', when at the end of the for-loop, I am trying to save all for-loop results in a vector. However when I run the code without that last line, it seems to recognise the variable 'avg'. Any ideas? Thanks in advance for your help. Below is the code.
P_pdf=[];
%Inices with NaN
idxnan=find(isnan(P_b));
for i=1:size(idxnan,1)-1
%Indices of numeric values
idxlow=idxnan(i)+1;
idxup=idxnan(i+1)-1;
%Group P_b Matrices according to NaN values
P_mat=P_b(idxlow:idxup);
%Reject empty matrices and treat singular values
if size(P_mat)==[1,1];
avg=P_mat;
elseif size(P_mat)==[0,0];
avg=NaN;
%Create distribution fit
pdf=fitdist(P_mat,'Normal');
avg=pdf.mu;
end
P_pdf=[P_pdf;avg];
end
Accepted Answer
More Answers (1)
Kosta
on 21 Jan 2017
1 Comment
Note that this code is not robust (e.g. it cannot cope with sequential NaN), nor efficient due to the concatenation inside the loop. In particular this is very poor code:
size(P_mat)==size(zeros(0,1))
Hard to read, hard to comprehend, and pointlessly complicated. See my answer and comments for much simpler code.
Categories
Find more on Creating and Concatenating Matrices 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!