How do you replace vector values?

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 个评论

Sounds like a homework question.. What have you done so far?
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.

请先登录,再进行评论。

 采纳的回答

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 个)

类别

帮助中心File Exchange 中查找有关 Get Started with MATLAB 的更多信息

产品

标签

Community Treasure Hunt

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

Start Hunting!

Translated by