MATLAB: A problem with a matrix

arrayfor loopmatrixmatrix manipulation

Hello. I am doing research connected with magnetic observatory data. I have 50 observatories and each of them produces 12 directories a year (for every month) with 30 files inside. That is why I need a loop. I downloaded data from the files successfully and counted a "MA-value" in a Class.
for k=1:1:12
meas=CCmpNew(1000,rect,0); %MA-value in a class
a = find(meas<0.4);
for i=1:kmax %kmax is the number of days in a month
b = a>(i-1)*1440 & a<=i*1440;
n(i)=sum(b)/1440;
for j=1:kmax*1440
if j>(i-1)*1440 && j<=i*1440
if meas(j)>0.55
n(i)=0;
end
end
end
end
[N,I]=sort(n,'descend');
for d=1:nnz(N) % It seems to me that the problem is in this loop.
kdu_I(d)=I(d);
kdu_N(d)=N(d);
K_(d)=k;
end
C=[K_' kdu_I' kdu_n'];
dlmwrite('path',C,'-append');
end
The problem is that when I write C matrix (actually, append it to file), if on some iteration there were less elements in C than on the previous iteration, the programme completes C up to the dimension of it on the previous iteration. How can I fix it? Could you please help me with this? I know my mistake is a silly one, but I'm beginner…

Best Answer

The problem is not with C, it's with the kdu_I, kdu_N and K_ and potentially n (seriously, what useless names! See my comments to the question) which are never initialised and just grow as required (but never shrink) on each iteration of the loops.
n = zero(1, kmax);
for i = ...
%...
[N, I] = ...
kdu_I = zeros(1, nnz(N));
kdu_N = zeros(1, nnz(N));
K_ = zeros(1, nnz(N));
for d = ...
would fix the problem.
However, I'm fairly certain that none of the loops are necessary but because of the lack of comments, indentation, and poor variable names, I've not tried to understand what exactly you are doing (see comment to question). Certainly, the whole d loop + variable initialisation above + assignment to C can be replaced by the much simpler:
C = [repmat(k, nnz(N), 1), nonzeros(N), I(1:nnz(N)).'];
If you make the rest of the code clearer you'll probably get suggestions on how to simplify it.