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

조회 수: 4(최근 30일)
Charles 22 Apr 2019
댓글: Charles 25 Apr 2019
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 22 Apr 2019
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 25 Apr 2019
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

댓글을 달려면 로그인하십시오.

R2018a

### Community Treasure Hunt

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

Start Hunting!