How do you replace vector values?

조회 수: 13 (최근 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 CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by