# Is this correct?

조회 수: 1(최근 30일)
Allison Sims 2022년 7월 18일
댓글: Chunru 2022년 7월 18일
Use loops to compute and plot (not animated)the following piecewise function for -15<=x<=15 .
F(x)={5x, x<0
{x^2, 0<=x<2
{ 2lnx, x>=2
My code:
x=-15:15;
if x<0;
5*x;
elseif x>=0 & x<2
y=x^2;
else x>=2;
y=2*log(x);
end
plot(x,y)
Warning: Imaginary parts of complex X and/or Y arguments ignored. ##### 댓글 수: 4표시숨기기 이전 댓글 수: 3
Chunru 2022년 7월 18일
Although the code is not doing what it intends to, the code can be run and MATLAB only gives a warning message (orange color).

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

### 채택된 답변

Chunru 2022년 7월 18일
x=-15:15;
y = zeros(size(x));
% This is more MATLAB way
idx = x<0;
y(idx) = 5 * x(idx);
idx = x>=0 & x<2;
y(idx) =x(idx).^2;
idx = x>=2;
y(idx) = 2*log(x(idx));
plot(x,y) % This is more conventional way (some othter programming language)
x=-15:15;
y = zeros(size(x));
for i=1:length(x)
if x(i)<0
y(i) = 5 * x(i);
elseif x(i)>=0 & x(i)<2
y(i) =x(i).^2;
elseif x(i)>=2;
y(i) = 2*log(x(i));
end
end
figure
plot(x,y) ##### 댓글 수: 1표시숨기기 없음
Allison Sims 2022년 7월 18일
That makes more sense thank you!

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

### 추가 답변(1개)

M.B 2022년 7월 18일
x = -15:1:15;% init x
y = nan*x;% init y to be of same size as x
for index = -15:15;
if index<0;
y(index+16) = 5*index;
elseif index>=0 & index<2
y(index+16) = index^2;
else index>=2;
y(index+16) = 2*log(index);
end
end
plot(x,y) ##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Chunru 2022년 7월 18일
The "index" is the loop variable the code uses and it need to be added with 16 in order to become array index (which is 1,2,...31). It's working code, but it may be further improved.

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

### 범주

Find more on Loops and Conditional Statements in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!