Index Vector in MATLAB

조회 수: 1 (최근 30일)
Justine Schneider
Justine Schneider 2017년 7월 31일
댓글: Star Strider 2017년 7월 31일
How do I index a vector in a for loop? I should be able to call the first entry of the vector a with a(1); however, I get an error when I have this as my for requirement. The error says unbalanced or unexpected parenthesis.
Here is a simplified version of my code.
a = [1 2 3]; b = [4 5 6];
for a(1) AND b(1);
suma = a + 1;
sumb = b +1;
end

채택된 답변

Star Strider
Star Strider 2017년 7월 31일
I do not understand what you want to do.
One of these should work:
a = [1 2 3]; b = [4 5 6];
for k = 1:min([numel(a) numel(b)])
suma = a(k) + 1;
sumb = b(k) + 1;
end
or:
suma = 0; sumb = 0;
for k = 1:min([numel(a) numel(b)])
suma = a(k) + suma;
sumb = b(k) + sumb;
end
or:
suma = sum(a);
sumb = sum(b);
or maybe something else ...
  댓글 수: 3
Justine Schneider
Justine Schneider 2017년 7월 31일
... from your first MATLAB code answer.
Star Strider
Star Strider 2017년 7월 31일
That simply prevents the index from reading a shorter vector beyond the number of elements it has. (Here, they are both the same size.)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by