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

2 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by