Azzera filtri
Azzera filtri

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

2 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

KSSV
KSSV il 24 Ago 2022
Modificato: KSSV il 24 Ago 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 Commenti
KSSV
KSSV il 24 Ago 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 il 24 Ago 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.

Accedi per commentare.

Più risposte (0)

Prodotti


Release

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by