I want to plot a graph for a function which varies according to the range of the variable (Like a piecewise function)

조회 수: 2 (최근 30일)
function trial2
c=2800;c1=1200;
pshi_i=-180:0.5:180;
t_i=50-(5/18)*pshi_i;
pshi=-180;
if pshi>=-55||pshi<=55
Pt_i=c*cosd(pshi);
pshi=pshi+0.5;
elseif pshi<-55||pshi55
Pt_i=0;
pshi=pshi+0.5;
end
plot(t_i,Pt_i,'*')
end
I tried with this code but the function just stick to the first value of function i give irrespective of the condition mentioned(has become a constant function rather than a varying piecewise function). Have been trying for the past 2 days but the result is the same.

채택된 답변

Yazan
Yazan 2021년 7월 2일
That is because your first condition is the most general (or inclusive). The second condition is satisfied when the tested value is less than -55, but any value less than -55 is less than 55, so the first condition is satisfied (note that you are using the operator OR in the conditions) and Matlab never tests the second condition.
  댓글 수: 2
sai venkat
sai venkat 2021년 7월 2일
I have tried using for loop but it just gives out the final value of the function for the final value of the variable. Can you suggest the best way of approach for this problem.
Yazan
Yazan 2021년 7월 2일
It is not about the looping. Your conditions are not well-posed. Just write your conditions mathematically first for us to be able to help.

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

추가 답변 (1개)

Steven Lord
Steven Lord 2021년 7월 2일
You can operate on a vector of values using logical indexing with a mask for each of your conditions.
% x data
d = 0:360;
% Preallocate the y data
y = zeros(size(d));
% Now select each quadrant in turn
quadrant1 = (0 <= d) & (d <= 90);
y(quadrant1) = sind(d(quadrant1));
quadrant2 = (90 <= d) & (d <= 180);
y(quadrant2) = 1 + cosd(d(quadrant2));
quadrant3 = (180 <= d) & (d <= 270);
y(quadrant3) = 1 + sind(d(quadrant3)) + cosd(d(quadrant3));
quadrant4 = (270 <= d) & (d <= 360);
y(quadrant4) = 2*(1 + sind(d(quadrant4)) - cosd(d(quadrant4)));
plot(d, y)
xline(90, 'r:'); xline(180, 'r:'); xline(270, 'r:')
You can see that the function being plotted changes at multiples of 90 (the red dotted lines).
  댓글 수: 1
sai venkat
sai venkat 2021년 7월 2일
Yeah. Now I understand how to operate on such kind of functions. I will try to use this method in my code. Thankyou.

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

카테고리

Help CenterFile Exchange에서 Beamforming and Direction of Arrival Estimation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by