Clear Filters
Clear Filters

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

2 views (last 30 days)
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.

Accepted Answer

KSSV
KSSV on 24 Aug 2022
Edited: KSSV on 24 Aug 2022
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 Comments
KSSV
KSSV on 24 Aug 2022
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 on 24 Aug 2022
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.

Sign in to comment.

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!