How do you replace vector values?

21 ビュー (過去 30 日間)
Madeline
Madeline 2012 年 10 月 9 日
Consider the following vector:
A=[6 8 12 -9 0 5 4 -3 7 -1]
Write a program using a for loop to produce a new vector, B which is related to A in the following way: All values of A which are not less than 1 should be replaced with the natural logarithm of that number, all numbers that are less than 1 should be replaced with the original number plus 20. Output the new vector.
  2 件のコメント
Thomas
Thomas 2012 年 10 月 9 日
Sounds like a homework question.. What have you done so far?
Madeline
Madeline 2012 年 10 月 9 日
This is what I have so far:
A = [6 8 12 -9 0 5 4 -3 7 -1];
k=1;
p=20;
for A
true(A>1)
Bvector=k.*log(A);
for A
false(A>1)
Bvector=p+A;
end
end
I know it's incorrect but one of the people in my group has the correct code in a while loop.
A=[6,8,12,-9,0,5,4,-3,7,-1];
n=1;
while n<=length(A)
if A(n)<1
A(n)=A(n)+20;
else
A(n)=log(A(n));
end
n=n+1;
end
disp(A)
So now I can't figure out how to write the code using a for loop.

サインインしてコメントする。

採用された回答

Matt Tearle
Matt Tearle 2012 年 10 月 9 日
What you have inside the while loop is basically what you need:
if A(n)<1
A(n)=A(n)+20;
else
A(n)=log(A(n));
end
You just need to convert the while structure to for. The strange thing is that for is much simpler. You want to loop over n from 1 to length(A). I'm not sure I can say much more than that without just doing it for you.
However, one other thing: the assignment says to produce a new vector B.
And while I'm here... I hate these kinds of assignments. I really hope that your instructor makes it absolutely clear that you should not use a loop for this kind of operation. Here it is done properly:
A = [6,8,12,-9,0,5,4,-3,7,-1];
B = A;
idx = (B<1);
B(idx) = B(idx) + 20;
B(~idx) = log(B(~idx));

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by