How can I Write a code that will allow a vector of positive integers in x, as a user input, to evaluate the equation listed below.For odd numbers we will use the following equation

조회 수: 4 (최근 30일)
x= input('\nPlease input a 5 values in vector notation:');
i = 1;
for i = 1:5
if rem(i,2) ==1; i = 2.*(i.^2) + 8*i - 3;
if rem(i,2)==0;
i = 2.*(i.^2) - 8*i + 3;
end
end
i=i+1
end
disp(i)
  댓글 수: 3
John Nowak
John Nowak 2019년 9월 18일
Sorry the question did not all paste.. the full question is:
How can I Write a code that will allow a vector of positive integers in x, as a user input, to evaluate the equation listed below. For odd numbers we will use the following equation: 2x^2 + 8x - 3
For even numbers we will use the following equation
2x^2 - 8x + 3.
I am stumped

댓글을 달려면 로그인하십시오.

채택된 답변

dpb
dpb 2019년 9월 18일
x= input('\nPlease input a 5 values in vector notation:');
b=nan(size(x)); % initialize to something
isodd=mod(x,2)==1;
y(isodd) =polyval([2 8 -3],x(isodd); % evaluate 2x.^2 + 8x - 3 for odd x
y(~isodd)=polyval([2 -8 3],x(~isodd); % evaluate 2x.^2 - 8x + 3 for even x
disp(y)
  댓글 수: 3
John Nowak
John Nowak 2019년 9월 18일
is there anyway you write this code as an if else statement?
thanks!
dpb
dpb 2019년 9월 18일
Sure... :)
Just carry on as you began with rough93 pattern incorporating my comments...since it is homework, let's see your continuing work towards a solution rather than just "giving away the store"....will continue to provide hints or answer specific questions other than "just do it"... :)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

rough93
rough93 2019년 9월 18일
It looks like you're using i within your calculations when you should be using x. Assuming your vecor input is [1 2 3 4 5]:
i = 1;
for i = 1:5
if rem(x(1),2) ==1; x = 2.*(x.^2) + 8*x - 3;
if rem(x,2)==0;
x = 2.*(x.^2) - 8*x + 3;
end
end
i=i+1
end
You may also want to make your second if an ifelse and add an else condition to clean up the code and prevent errors.
  댓글 수: 1
dpb
dpb 2019년 9월 18일
편집: dpb 2019년 9월 18일
The if above for rem(x,2)==0 won't work as it returns a logical vector which will be true only if all elements are true. Need to test x(i) in the loop.
The assignment is also global and overwrites the input x vector in the calculations.
Also incrementing i is automagic in the loop for expression and neither the initialization before the loop nor the incrementing statement are of any use and should be eliminated entirely.

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by