フィルターのクリア

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

6 ビュー (過去 30 日間)
Albert
Albert 2017 年 10 月 13 日
コメント済み: Albert 2017 年 10 月 14 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by