How do you replace vector values?

21 views (last 30 days)
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
Thomas
Thomas on 9 Oct 2012
Sounds like a homework question.. What have you done so far?
Madeline
Madeline on 9 Oct 2012
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.

Sign in to comment.

Accepted Answer

Matt Tearle
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));

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!