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