필터 지우기
필터 지우기

In the command window, use a for loop to fill a vector v with the squares of 2, 3, 4, 5.

조회 수: 6 (최근 30일)
Hi there, I am trying to understand an in class example put am having difficulties completing the code the question is :
In the command window, use a for loop to fill a vector v with the squares of 2, 3, 4, 5. Start with
v = zeros(1,4)
After entering your for loop in the command window, v should be:
>> v
v=
4 9 16 25
Heres what I have so far:
>> v=zeros(1,4);
i=1;
v(i)=2;
i=2;
v(i)=3;
i=3;
v(i)=4
i=4;
v(i)=5;
v =
2 3 4 5
for i=1:4 v=v(i).*v(i); disp(v); end;
however I am getting the message "Index exceeds matrix dimensions."
Can someone offer me some tips with approaching this problem

채택된 답변

Jonathan Chin
Jonathan Chin 2017년 10월 14일
you are overwriting your vector instead of filling the array
v=zeros(1,4); % this is [0,0,0,0]
v=[2,3,4,5]% pre-assign values
when you index into v with the for loop variable i you overwrite v, see below
for i =1:4
v=v(i).*v(i); %<- this here overwrites your variable v completely on the first loop
disp(v)%making it 2*2 when i =1, when i becomes 2 there is no longer a second index
end
%corrected version
for i =1:4
v(i)=v(i).*v(i); %<- this here replaces your value at index i
disp(v)
end
Also another way to do this problem for future reference is to do vector math
v=[2,3,4,5]
v = v.*v

추가 답변 (1개)

Walter Roberson
Walter Roberson 2017년 10월 14일
for i=1:4; v(i)=v(i).*v(i); end; v

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by