Populate matrix with non-zero elements from previous matrix

I have a 7567*32 matrix in which every row has 4 non-zero elements and the rest are zeros. I want to create a 7567*4 matrix that is populated only with the non-zero elements from the previous matrix. Is there a way to do so?

 채택된 답변

Stephen23
Stephen23 2018년 4월 13일
편집: Stephen23 2018년 4월 13일
I guess you want to keep those non-zero values in the same rows in which case try this, where M is your matrix:
Z = M.';
Z = reshape(Z(Z~=0),4,7567).'

댓글 수: 3

Nice thank you. But apparently some values I have to retrieve from the original matrix are zeros. So what I have to do is basically this: I have one matrix with zeros, ones and minus ones, and another matrix with returns in the same location as the ones and minus ones of the previous matrix. For example: [0 1 -1 1 0 -1; -1 1 0 0 -1 1; 0 0 1 1 -1 -1] and [0 0.2 -0.3 0.4 0 -0.5; -0.6 1.3 0 0 0.1 1.5; 0 0 0.9 0.8 -0.1 -0.2]. Now I have to create that 4-column (3 rows in this case) matrix with the values of the second matrix, given that they are in the same location of the nonzeros in the first matrix. Is this feasible?
Thx a lot
Generate the indices from the first matrix, and get the values from the second matrix:
>> X = [0 1 -1 1 0 -1; -1 1 0 0 -1 1; 0 0 1 1 -1 -1]
X =
0 1 -1 1 0 -1
-1 1 0 0 -1 1
0 0 1 1 -1 -1
>> M = [0 0.2 -0.3 0.4 0 -0.5; -0.6 1.3 0 0 0.1 1.5; 0 0 0.9 0.8 -0.1 -0.2]
M =
0.00000 0.20000 -0.30000 0.40000 0.00000 -0.50000
-0.60000 1.30000 0.00000 0.00000 0.10000 1.50000
0.00000 0.00000 0.90000 0.80000 -0.10000 -0.20000
>> Z = M.';
>> Z = reshape(Z(0~=X.'),4,[]).'
Z =
0.20000 -0.30000 0.40000 -0.50000
-0.60000 1.30000 0.10000 1.50000
0.90000 0.80000 -0.10000 -0.20000
Tomás Nunes's "Answer" moved here:
Thank you so much, you're the best

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2018년 4월 13일

댓글:

2018년 4월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by