how can I merge matrices

조회 수: 1 (최근 30일)
Elbr
Elbr 2015년 5월 13일
편집: Elbr 2015년 5월 22일
Z is a vector and X is a matrix
for h = 1:length(Z)
[D , E] = find(Z(h) == X)
end
vector D and E overwrite in every loop. how can i conserve them in a vector?

채택된 답변

Stephen23
Stephen23 2015년 5월 13일
편집: Stephen23 2015년 5월 13일
Even better would be to avoid the loop entirely by using bsxfun:
>> F = [1,2,3]
F =
1 2 3
>> B = [0,1;3,2;0,Inf;9,8]
B =
0 1
3 2
0 Inf
9 8
>> out = bsxfun(@eq,B,reshape(F,1,1,[]));
>> idx = find(out)
idx =
5
14
18
And of course you can use ind2sub to get more specific index information:
>> [row,col,pag] = ind2sub(size(out),idx)
row =
1
2
2
col =
2
2
1
pag =
1
2
3
  댓글 수: 1
Stephen23
Stephen23 2015년 5월 13일
편집: Stephen23 2015년 5월 13일
I do not understand what you mean by "there are to many numbers in vector the row and column". Your original code would detect all values that match between B and F. That is what my code does too! If you want the code to do something else, then you need to specify what it should do.
The method that I gave in my answer does not depend on the size of B or F. They do not have to have any matching dimensions. Lets have a look at your example data (my code is exactly the same as before):
B = [-2, -2, -2, -1, -2, -2, -2, -2
-2, 0, 5, -1, 12, 14, 1, -2
-2, 5, 15, -1, 17, 14, 8, -2
-2, 15, 12, -1, 15, 0, 14, -2
-1, -1, -1, -1, 7, 14, 8, -2
-2, 8, 14, -1, 17, 12, 1, -2
-2, 9, 0, -1, 1, 4, 1, -2
-2, -2, -2, -1, -2, -2, -2, -2];
F = [ 5, 1, 5, 7, 1, 1, 4, 1];
out = bsxfun(@eq,B,reshape(F,1,1,[]));
idx = find(out);
[row,col,pag] = ind2sub(size(out),idx);
and then run the script, and try this in the command window:
>> [row,col,pag]
ans =
3 2 1
2 3 1
7 5 2
2 7 2
6 7 2
7 7 2
3 2 3
2 3 3
5 5 4
7 5 5
2 7 5
6 7 5
7 7 5
7 5 6
2 7 6
6 7 6
7 7 6
7 6 7
7 5 8
2 7 8
6 7 8
7 7 8
Each row corresponds to one matching value. For example, have a look at the first row: 3,2,1. This tells us that row three and col two in B (==5) is equal to the first element of F (==5). This has located all values that are equal in B and F.

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

추가 답변 (1개)

Ingrid
Ingrid 2015년 5월 13일
[D(h), E(h)] = find(F(h)==B);
  댓글 수: 1
Stephen23
Stephen23 2015년 5월 13일
This will fail for any case where find returns non-scalar values, e.g. if more than one match is found, or no matches are found.

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

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by