Hello!
I have a problem with matrix operation. I have a complex matrix M(n,m), I also have a matrix MM(n,m) with where each row have positions for each row where I want to keep the value for matrix M. Shown i this example
M=[1 2 3;3 2 1;2 3 1];
MM=[1 0 0;1 3 0;3 0 0];
What I want out of this is:
R=[1 0 0;3 0 1;0 0 1];
I have tried to solve this problem but obviously I am not skilled enough. Please help me.
Regards Björn

 Réponse acceptée

Stephen23
Stephen23 le 25 Mar 2016
Modifié(e) : Stephen23 le 25 Mar 2016

0 votes

M = [1,2,3;3,2,1;2,3,1];
X = [1,0,0;1,3,0;3,0,0];
%
[row,col] = find(X);
col = X(X>0);
idx = sub2ind(size(M),row,col);
R = zeros(size(M));
R(idx) = M(idx);
creates this:
>> R
R =
1 0 0
3 0 1
0 0 1

2 commentaires

Björn Olsson
Björn Olsson le 25 Mar 2016
Modifié(e) : Stephen23 le 26 Mar 2016
First of all, thank you for your answer!
I guess my example was not a good one, your code works perfectly for my example but not for the real thing. I get this message:
Error using sub2ind (line 52) Out of range subscript.
Error in testklippsaltholmen160325 (line 136) idx=sub2ind(size(Xcut),row,col);
My real matrix with the information I seek is M(80,5512); and my matrix with the information which row and column the information should be taken from is X(80,5512); My idea is that I want to pick out some for me important parts of the information, that is the easy part, but I want the information to stay at its position and I want the other not picked information parts to be zero. The matrix with the row/column-info is built as this example:
[1 34 500 1056 5510 0 0 0 0;
1 70 5000 0 0 0 0 0 0;
1 300 500 600 1000 3000 0 0 0;];
Just for the record so the information matrix is complex. I don´t think that matters.
Regards Björn
Stephen23
Stephen23 le 26 Mar 2016
Modifié(e) : Stephen23 le 26 Mar 2016
It sounds as if some of the indices are outside the size of the data matrix. If you upload some sample data then I can see what the problem is, and actually run the code. Without data to test code on I have to rely on my mind-reading abilities, which are a bit rusty these days.
Make a new comment, click the paperclip button, then both Choose file and Attach file. Then I can help you.
" but I want the information to stay at its position and I want the other not picked information parts to be zero" I thought that is what my code does, or have I missed something?

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Random Number Generation dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by