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

10 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Jonathan Chin
Jonathan Chin el 14 de Oct. de 2017
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

Más respuestas (1)

Walter Roberson
Walter Roberson el 14 de Oct. de 2017
for i=1:4; v(i)=v(i).*v(i); end; v

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by