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 日

0 投票

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 日
編集済み: Fischer Zheng 2015 年 9 月 17 日
Looping is not that good in my case as there are 200k rows each time.
I was thinking about using ind2sub and accumarry to make it happen.
Stephen23
Stephen23 2015 年 9 月 17 日
MATLAB does not have a shift operator, let alone a vectorized version of it. You will have to create your own. While there could be solutions with cell arrays, cellfun, accumarray and the like, probably the fastest and least obfuscated solution would be to use a simple loop.
Star Strider
Star Strider 2015 年 9 月 17 日
I doubt if either ind2sub or accumarray or arrayfun or any of the others would work in this instance. Considering that you’re doing a different shift on each row, there is no way to vectorise this operation.
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 日

0 投票

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,

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2015 年 9 月 17 日

編集済み:

2015 年 9 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by