Compare some parts from one row in two matrices
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Clémentine OU
el 30 de Ag. de 2017
Editada: Clémentine OU
el 1 de Sept. de 2017
Hello, I have two matrices, one is
K=[1 4 2 0 1;1 4 0 0 1;2 4 0 0 1;2 4 3 0 1;5 4 2 0 2];
the other is
L=[1 4 0 0 1; 2 4 0 0 1; 4 2 0 0 2].
I want to do somethings:
- get one row from L in a loop;
- extract the first column and the last column of this row;
- compare the extracted number with the related location in every row of K;
- If the numbers are matched, get the index from K.Can anyone help me how to do that, please?Thanks in advance.
7 comentarios
Respuesta aceptada
José-Luis
el 30 de Ag. de 2017
K_sub = K(:,[1,end]);
L_sub = L(:,[1,end])
[ii,kk] = size(L_sub);
L_sub=reshape(L_sub',[1,kk,ii]);
result = squeeze(sum(bsxfun(@eq,K_sub,L_sub),2) == 2)
Where each column will be a logical index to where your condition is true.
2 comentarios
Clémentine OU
el 31 de Ag. de 2017
Editada: Clémentine OU
el 31 de Ag. de 2017
José-Luis
el 31 de Ag. de 2017
Editada: José-Luis
el 31 de Ag. de 2017
You don't need mm. You still need to perform the sum along the second dimension.
K_sub = K(:,[1,2,end])
L_sub = L(:,[1,2,end])
[ii,kk] = size(L_sub)
L_sub=reshape(L_sub',[1,kk,ii])
result = squeeze(sum(bsxfun(@eq,K_sub,L_sub),2) == 3)
Please accept the answer that best solves your problem.
As an exercise, you could try to adapt it so you can specify the column indexes instead of hardcoding them.
Más respuestas (1)
Jan
el 30 de Ag. de 2017
K = [1 4 2 0 1;1 4 0 0 1;2 4 0 0 1;2 4 3 0 1;5 4 2 0 2];
L = [1 4 0 0 1; 2 4 0 0 1; 4 2 0 0 2];
[match, locK] = ismember(L(:, [1,end]), K(:, [1,end]), 'rows')
Result = locK(match);
9 comentarios
Jan
el 31 de Ag. de 2017
"OP" is the "original poster", the person who has asked the question.
"Homework" is a question given to pupils or students to be solved at home. If a user posts a homework question, the forum tend to explain, who it can be solved by your own. Posting a working solution could cause troubles, because you submitting this solution would be cheating and you had missed the chance to learn Matlab.
It is strange, that you do not want to post the wanted output for the shown input, although we have asked repeatedly for this. This is not useful. What's wrong with provided the information, which would allow for solving the problem?
Following your explanations here, this is a job for ismember('rows') and I still think that ismember('rows') solves the problem directly. At least you did not explain, what the differences between the result and your wanted results is.
Clémentine OU
el 1 de Sept. de 2017
Editada: Clémentine OU
el 1 de Sept. de 2017
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!