0

I want to save the following for-loop results in a new matrix using Matlab, how can I do that or any other suggestions?

Where X is a 5467-by-513 matrix , id is a 143-by-1 vector and wkno is a 44-by-1 vector

for i=1:size(id,1);
    for j=1:size(wkno,1);
        tst= X(:,1)==id(i) & X(:,2)==wkno(j);
        M=mean(X(tst,:));
    end
end
Dan
  • 45,079
  • 17
  • 88
  • 157
Bali S
  • 1

1 Answers1

1

Just make sure you actually save the things to a matrix instead of a scalar-variable, i.e. add the subscript indices to the variable you're saving to:

for ii=1:size(id,1);
    for jj=1:size(wkno,1);
        tst(ii,jj)= X(:,1)==id(ii,1) & X(:,2)==wkno(jj,1);
        M(ii,jj)=mean(X(tst,:));
    end
end

Not that I refrained from using i and j as a variable, since this is a bad idea. I added the ,1 to id and wkno, to make sure you use them as column variables. This is a good habit to get into, because single indices will go wrong when you have a multi-dimensional array.

Community
  • 1
  • 1
Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • Many thanks for the suggestion and answer., However when I run the above mentioned script I get error :Subscripted assignment dimension mismatch. It may be due to when it looks for no. of rows to calculate mean, if it finds only one row, then the calculated mean is scalar? If so I want to keep the original row, instead of calculating the mean, Could you please help in this regard how to adjust the script? Thanks again – Bali S Oct 09 '15 at 10:13