Shift array to left or right, keep length and feel zero empty area

225 ビュー (過去 30 日間)
Nik Rocky
Nik Rocky 2020 年 12 月 6 日
回答済み: Steven Lord 2023 年 11 月 13 日
Hello,
I have an array:
A = [1 2 3 4 5 6 7 8 9];
I want create B array from A
B = [0 0 1 2 3 4 5 6 7];
or
B = [3 4 5 6 7 8 9 0 0];
How it is possible?
circshift dont feel zeros

採用された回答

Cris LaPierre
Cris LaPierre 2020 年 12 月 6 日
I'm not aware of a function that will do exactly what you describe. However, the final result is still possible if you are willing to break the process up into steps.
A = [1 2 3 4 5 6 7 8 9];
B = zeros(size(A));
B(3:end) = A(1:7)
B = 1×9
0 0 1 2 3 4 5 6 7
% or
n = -2;
B = circshift(A,n);
if n>0
B(1:n) = 0
else
B(end+n+1:end) = 0
end
B = 1×9
3 4 5 6 7 8 9 0 0
  2 件のコメント
Nik Rocky
Nik Rocky 2020 年 12 月 6 日
Beautiful! Thank you so much!
Stephen23
Stephen23 2023 年 11 月 12 日
Note that the IF..ELSE..END can be replaced with one line:
A = 1:9;
n = -2;
B = circshift(A,n);
B([1:n,end+n+1:end]) = 0
B = 1×9
3 4 5 6 7 8 9 0 0
n = +2;
B = circshift(A,n);
B([1:n,end+n+1:end]) = 0
B = 1×9
0 0 1 2 3 4 5 6 7

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

その他の回答 (2 件)

Aamod
Aamod 2023 年 10 月 13 日
Same code for a 2D matrix - shift by shift values and zero pad the extra area.
function Eout = circshiftzeropad(Ein,shifty,shiftx)
%function Eout = circshiftzeropad(Ein,shifty,shiftx)
%shifts and zeropads an array
Eout = circshift(Ein,[shifty shiftx]);
if shiftx <0
Eout(:,(end+shiftx):end)= 0;
else
Eout(:,(1:shiftx))= 0;
end
if shifty <0
Eout((end+shifty):end,:)= 0;
else
Eout((1:shifty),:)= 0;
end
  2 件のコメント
Enzo
Enzo 2023 年 11 月 12 日
Thanks a lot, it helped me !
Aamod
Aamod 2023 年 11 月 13 日
Wonderful!

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


Steven Lord
Steven Lord 2023 年 11 月 13 日
If you're using release R2023b or later you could use paddata.
A = [1 2 3 4 5 6 7 8 9];
B = paddata(A(1:end-2), numel(A), Side="leading")
B = 1×9
0 0 1 2 3 4 5 6 7
C = paddata(A(3:end), numel(A)) % Default is Side="trailing"
C = 1×9
3 4 5 6 7 8 9 0 0
If you object to the fact that I hard-coded "1:end-2" and "3:end":
n = 2;
B = paddata(A(1:(end-n)), numel(A), Side="leading")
B = 1×9
0 0 1 2 3 4 5 6 7
C = paddata(A((1+n):end), numel(A))
C = 1×9
3 4 5 6 7 8 9 0 0

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by