How to add a row vector for indexing

2 次查看(过去 30 天)
How to add a row vector for indexing C by M when my M is 4 dimensional ? any help will be thankful.
F=random('exp',1,3,3,4);
C=F*100
M=bsxfun(@times, C./cumsum(C,3) , reshape(1:4,1,1,[]) );
[vec,idx] = max(M,[],1); % value and row index of max in each column.
S = size(M); % size of input array.
idx = idx + S(1)*(0:S(2)-1); % convert row index into linear index !
C(idx); % use linear index to get elements of C.
  2 个评论
Jan
Jan 2019-2-12
What exactly is your question? What do you want to add to what? Does the posted code do what you expect? If not, what do you want to change?
Ashraf Sherif
Ashraf Sherif 2019-2-12
thank you Jan for inquires, well I have a matrix C is a 3 by 3 random variables with 4 iterations, at each iterate each element devided by it is average and collected at matrix M which done by below code
M=bsxfun(@times, C./cumsum(C,3) , reshape(1:4,1,1,[]) );
I want to index C by the maximum values in each column of matrix M, by this code
[vec,idx] = max(M,[],1);
so far all are OK but to continue the indexing by using the below code
idx = idx + S(1)*(0:S(2)-1);
which to convert row index into linear index, an error appears
Error using +
Matrix dimensions must agree.
Error in Untitled5 (line 26)
idx = idx + S(1)*(0:S(2)-1);
some told me I have to add a row because different dimensions but i couldn't do that, and I am looking for some hlep or if there are an other methode to do whole this operation.

请先登录,再进行评论。

采纳的回答

Matt J
Matt J 2019-2-12
编辑:Matt J 2019-2-12
I would do it this way,
idx=bsxfun(@eq, M, max(M,[],1) );
C(idx),
  2 个评论
Matt J
Matt J 2019-2-12
编辑:Matt J 2019-2-12
I would also recommend that you learn how to use BSXFUN since you are running into it again and again, and since apparently you cannot upgrade to a more recent Matlab version where it is less required.
Ashraf Sherif
Ashraf Sherif 2019-2-13
Thank you very much Matt J for you advice and help

请先登录,再进行评论。

更多回答(0 个)

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by