필터 지우기
필터 지우기

Maxtrix copy and manipulation

조회 수: 1 (최근 30일)
Fischer Zheng
Fischer Zheng 2015년 9월 17일
편집: Matt J 2015년 9월 18일
I have one matrix and one vector. I would like to shift the elements of row forward depending on the vector index.
M = [0 2 4 5;
0 4 7 9;
0 0 0 34];
v = [4 3 2];
Shift the elements of M forward, v(1) = 4 indicate start result with the 4th element of the row. Pad the end of row with zeros.
Result = [5 0 0 0;
7 9 0 0;
0 0 34 0]
How do I do this in the vectorized way?
Thanks, Fischer

채택된 답변

Star Strider
Star Strider 2015년 9월 17일
This uses a loop, but I can’t see how to do this without one:
M = [0 2 4 5; 0 4 7 9; 0 0 0 34];
v = [4 3 2];
c = size(M,2);
Result = zeros(size(M));
for k1 = 1:size(M,1)
Result(k1,1:c-v(k1)+1) = M(k1,v(k1):c);
end
  댓글 수: 5
Fischer Zheng
Fischer Zheng 2015년 9월 17일
You are right, too bad.
Star Strider
Star Strider 2015년 9월 17일
Thank you.
If you’re doing this once for each large matrix, save the shifted matrix to a .mat file. Then you can simply load the shifted matrix when you need it, rather than recalculating it each time.

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

추가 답변 (1개)

Matt J
Matt J 2015년 9월 17일
편집: Matt J 2015년 9월 18일
v=v(:);
[m,n]=size(M);
[I,J,S]=find(M);
J=J-v(I)+1;
idx=J>0;
Result=sparse(I(idx),J(idx),S(idx),m,n);
Result=full(Result); %optional
  댓글 수: 1
Fischer Zheng
Fischer Zheng 2015년 9월 17일
편집: Fischer Zheng 2015년 9월 17일
Thanks for the update. Let me take a look again.
Thanks,

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by