필터 지우기
필터 지우기

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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by