Indexing into a m x n array to find values using an array of row and column indices

1 次查看(过去 30 天)
I have a cell array A. and marrix B
A = [2,4,0.5,0.34;0.01,4,0.5,0.34;10,4,0.2,0.6;10,4,0.2,0.6;19,15,0.7,0.6]
B = [1,1;1,2;2,4;2,3;3,4;3,3;4,1;4,2;5,2;5,3]
I am trying to use the indices in matrix B, to index into Matrix A and return the values
C =
2 4
0.34 0.5
0.6 0.2
10 4
15 0.7
I then wish to add the values across columns and return a vector D
D =
6
0.54
0.8
14
15.7
i then wish to take each row element in C and divide it by its row total in D, and return the values in a matrix E
E =
2./6 4./6
0.34./0.54 0.5/0.54
0.6./0.8 0.2./0.8 ETC ETC
I have made a start but clear a look is the worng thing to do here in order to extract the values from A using the indcies in B. All help appreciated. Would cellfun work?
rowcolidx = B
rowcolidx=zeros(1,size(B,1));
for i = 1:size(B(1:end,:),1)
temp = A(rowcolidx(i,1),rowcolidx(i,2));
ReturnsVal = temp;
end

回答(1 个)

madhan ravi
madhan ravi 2019-4-22
编辑:madhan ravi 2019-4-22
Note: Your D seems to be wrong 0.34+0.5 == 0.84 not .54.
According to the example what you posted A and B are not cell array if it so then use cell2mat() and follow the following:
C = reshape(A(sub2ind(size(A),B(:,1),B(:,2))).',2,[]).';
D = sum(C,2);
E = C./D;
  1 个评论
Charles
Charles 2019-4-25
Thank you for this I am tryignt o figute out what reshpe and sub2idx do. I seem to get one long row vector whn i execute this line. I am reviwing now and looking a tthe matlab explanaition

请先登录,再进行评论。

类别

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

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by