필터 지우기
필터 지우기

Homework help - need help debugging it

조회 수: 1 (최근 30일)
Lin Jun Lee
Lin Jun Lee 2018년 12월 6일
편집: madhan ravi 2018년 12월 6일
The Question Given
Use the data below to perform the following:
x = [1 2 3 4 5 6 7 8 9 10];
y = [0.841 0.909 0.141 -0.756 -0.958 -0.279 0.656 0.989 0.412 -0.544];
  1. Plot the (x, y) data points as red squares
  2. Determine the sign of each y data point using the sign() function. You must use the sign() function. If the sign command returns a positive value, square the value of y. If the sign command returns a negative value, square root the absolute value of y.
  3. Plot the result as a blue solid line on the same plot produced in part A.
My Solution
%Data
x = [1 2 3 4 5 6 7 8 9 10];
y = [0.841 0.909 0.141 -0.756 -0.958 -0.279 0.656 0.989 0.412 -0.544];
%Plot the (x,y) data points as red squares
plot (x,y, 'rs')
title ('graph')
hold on
%Determine the sign of each y data point using the sign() function
a=sign(y)
%If statements (Part B)
if a==1;
y=(y^.2);
elseif a==-1;
y=sqrt(abs (y));
end
%Plot the second result on the same plot
plot (x,y, 'bl')
hold off
The Problem
It does seem that my graph is not showing as it should. All the values are positive, but from my understanding, they shouldn't.

채택된 답변

madhan ravi
madhan ravi 2018년 12월 6일
편집: madhan ravi 2018년 12월 6일
Use logical index instead of if and elseif:
x = [1 2 3 4 5 6 7 8 9 10];
y = [0.841 0.909 0.141 -0.756 -0.958 -0.279 0.656 0.989 0.412 -0.544];
%Plot the (x,y) data points as red squares
plot (x,y, 'rs')
title ('graph')
hold on
%Determine the sign of each y data point using the sign() function
a=sign(y);
%If statements (Part B)
y(a==1)=y(a==1).^2;
y(a==-1)=sqrt(abs(y(a==-1)));
%Plot the second result on the same plot
plot (x,y, 'bl')
hold off
  댓글 수: 2
Lin Jun Lee
Lin Jun Lee 2018년 12월 6일
Thanks! Just to check, if my understanding is correct, this code means
y(a==1)=y(a==1).^2;
"When y is positive, square y"
and
y(a==-1)=sqrt(abs(y(a==-1)));
"When y is negative, square root the absolute value of y"
Is there a reason why if statements and elseif statements can't be used? Is it because there are two variables or, what is the reason?
madhan ravi
madhan ravi 2018년 12월 6일
편집: madhan ravi 2018년 12월 6일
Anytime :) , Exactly! you understood it , if you want to use if and elseif statements you have to use a loop which is a bit more work. This is matlab! so learn to vectorize.

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

추가 답변 (1개)

MUHAMMED IRFAN
MUHAMMED IRFAN 2018년 12월 6일
Hey,
In the part B of your code, you might need a for loop to look through each of the element in a and check whether it is +1 or -1. Something like:
for i = 1:length(a)
Element = a(i);
% code to check for sign goes here.
end

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by