フィルターのクリア

Print or display a group of numbers contained in a vector with loops

2 ビュー (過去 30 日間)
Nat
Nat 2022 年 8 月 24 日
コメント済み: Nat 2022 年 8 月 24 日
Hi everyone,
I arranged a vector of 15 elements in total and I am asked to print the numbers in groups of 3.
a=[2 4 3 5 9 8 2 1 0 2 3 4 7 8 9];
For example, the first print would only print the first three numbers in that vector, then print the next three numbers again, and so on. Let's say: 2 4 3, then 5 9 8 and so on. Of course, I do understand I need to loop my program so it can print five groups (15 elements/3).
Maybe I don't have much experience and my logic understands the following code:
cont=1;
for i=1:length(a)/5
disp(a(cont))
cont=cont+3;
end
2 5 2
I failed since it's only printing the numeric value every three results (2 5 2 2 7) and it doesn't print the groups of numbers. I know that this should be done with a single for but I don't understand how I can organize the information.

採用された回答

KSSV
KSSV 2022 年 8 月 24 日
編集済み: KSSV 2022 年 8 月 24 日
REad about reshape
a = [2 4 3 5 9 8 2 1 0 2 3 4 7 8 9];
b = reshape(a,3,[])'
B = 5×3
2 4 3 5 9 8 2 1 0 2 3 4 7 8 9
  3 件のコメント
KSSV
KSSV 2022 年 8 月 24 日
a = [2 4 3 5 9 8 2 1 0 2 3 4 7 8 9];
idx = 0:3:length(a) ;
for i = 2:length(idx)
a(idx(i-1)+1:idx(i))
end
ans = 1×3
2 4 3
ans = 1×3
5 9 8
ans = 1×3
2 1 0
ans = 1×3
2 3 4
ans = 1×3
7 8 9
Nat
Nat 2022 年 8 月 24 日
Didn't tried creating a new variable with the length measurement so indexing appeared first in an index expression and that's incorrect.
It works! People can print all results separately with
a(idx(i-1)+1:idx(i))
Or just one result with 'display'.
disp(a(idx(i-1)+1:idx(i)))
I really appreciate your willingness. Thank you.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by