How do you replace vector values?
21 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Matt Tearle
on 9 Oct 2012
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 Comments
More Answers (0)
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!