Left-rotating a vector

16 ビュー (過去 30 日間)
Shuoze Xu
Shuoze Xu 2022 年 3 月 22 日
コメント済み: Shuoze Xu 2022 年 3 月 22 日
we define a vector A and create a new vector B containing the elements of A shifted one index to the left.
% As an example
A B
[ 1 2 3 4 ] [ 2 3 4 1 ]
[ 5 3 8 ] [ 3 8 5 ]
% My code
A = [1,2,3,4,5];
B = [];
for i = 2:length(A)
% A(1) = B(end);
B = [B A(i)];
end
disp(B);
% The program showed Array indices must be positive integers or logical values.
% i do not know how to improve my code
% Thank you all

採用された回答

Alan Stevens
Alan Stevens 2022 年 3 月 22 日
You define B as a null vector so it doesn't have an "end".
Try, simply
A = [1,2,3,4,5];
B = [A(2:end) A(1)]
B = 1×5
2 3 4 5 1
  2 件のコメント
Shuoze Xu
Shuoze Xu 2022 年 3 月 22 日
Thank you.
But i want to do it by using a for loop.
Do you have any suggestion?
Shuoze Xu
Shuoze Xu 2022 年 3 月 22 日
I think i know how to do it.
Thank you for your idea and help

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by