how can I merge matrices

1 visualizzazione (ultimi 30 giorni)
Elbr
Elbr il 13 Mag 2015
Modificato: Elbr il 22 Mag 2015
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?

Risposta accettata

Stephen23
Stephen23 il 13 Mag 2015
Modificato: Stephen23 il 13 Mag 2015
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 Commento
Stephen23
Stephen23 il 13 Mag 2015
Modificato: Stephen23 il 13 Mag 2015
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.

Accedi per commentare.

Più risposte (1)

Ingrid
Ingrid il 13 Mag 2015
[D(h), E(h)] = find(F(h)==B);
  1 Commento
Stephen23
Stephen23 il 13 Mag 2015
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.

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by