How to solve : Subscripted assignment dimension mismatch error

6 次查看(过去 30 天)
Hello,
I want to calculate mean of rows with multiple criteria. Below is the for loop which I am using, however I get error :Subscripted assignment dimension mismatch error. 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?
Where X is a 5467-by-513 matrix , id is a 143-by-1 vector and wkno is a 44-by-1 vector
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
Many thanks

采纳的回答

Thorsten
Thorsten 2015-10-12
编辑:Thorsten 2015-10-12
tst is a vector, so you cannot store it in a single scalar tst(ii,jj). Same for M(ii,jj). This may work:
M = nan(numel(id), numel(wkno), size(X,2));
for ii=1:size(id,1);
for jj=1:size(wkno,1);
tst = X(:,1)==id(ii,1) & X(:,2)==wkno(jj,1);
if sum(tst) == 1
M(ii,jj,:) = X(tst,:))
elseif sum(tst) > 1 % could be 0 if nothing is matching...
M(ii,jj,:)=mean(X(tst,:));
end
end
end
  3 个评论
Thorsten
Thorsten 2015-10-12
It depends on your data what makes senses. You could sum across the 3rd dimension, for example:
imshow(sum(M, 3), []);
Bali S
Bali S 2015-10-12
Thanks again Thorsten for your help, really appreciated. I have used reshape function to convert 2D matrix of dimension 6292 by 513, that is really I needed. Thank you

请先登录,再进行评论。

更多回答(1 个)

Walter Roberson
Walter Roberson 2015-10-12
It would be the other way around. When there is only one match then the mean calculated would be a scalar, and that is the case that would work. When there are multiple matches then the mean would be a vector with as many entries as the number of columns, and you cannot store a vector into M(ii,jj) as that is a single array location.

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by