How to add a row vector for indexing

2 views (last 30 days)
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 Comments
Jan
Jan on 12 Feb 2019
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 on 12 Feb 2019
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.

Sign in to comment.

Accepted Answer

Matt J
Matt J on 12 Feb 2019
Edited: Matt J on 12 Feb 2019
I would do it this way,
idx=bsxfun(@eq, M, max(M,[],1) );
C(idx),
  2 Comments
Matt J
Matt J on 12 Feb 2019
Edited: Matt J on 12 Feb 2019
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 on 13 Feb 2019
Thank you very much Matt J for you advice and help

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!