Maxtrix copy and manipulation
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Fischer Zheng
am 17 Sep. 2015
Bearbeitet: Matt J
am 18 Sep. 2015
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
0 Kommentare
Akzeptierte Antwort
Star Strider
am 17 Sep. 2015
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 Kommentare
Star Strider
am 17 Sep. 2015
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.
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!