How to code a ramp function?
조회 수: 132 (최근 30일)
이전 댓글 표시
Hi,
I tried to code a ramp function as attached herewith.
But getting an error
"Operands to the logical AND (&&) and OR (||) operators must be convertible to logical scalar values. Use the ANY
or ALL functions to reduce operands to logical scalar values."
Hence I need your valuable suggestion so as to run the same.
function r = ramp(t)
tstep = 10;
tmin = 0;
tmax = 10;
t = linspace(tmin,tmax,tstep);
if t<=4
H0=0.2*t;
end
if t>=5 && t<=7
H0=max(0,t);
end
if t>=8
H0=0.2*t;
end
plot(H0,t)
with regards,
rc
댓글 수: 0
채택된 답변
Walter Roberson
2023년 11월 8일
t = linspace(tmin,tmax,tstep);
t is a vector.
if t<=4
MATLAB treats that as equivalent to
if all(t<=4)
and the body of the if would be executed only if no entries in t are greater than 4. But with the particular values you used for linspace() there are some values greater than 4 in t, so the if would fail.
if t>=5 && t<=7
That would be treated like
if all(t>=5 && t<=7)
which would fail for vector t because && can only be used with scalars. If you had coded
if t>=5 & t<=7
then the & operation could succeed, returning a vector of values, and the statement would be equivalent to
if all(t>=5 & t<=7)
but that would fail beause there are some values outside that range.
H0=0.2*t;
That would take all of the vector t and multiply by 0.2, and asssign the vector result to H0. But that is not going to be assigning those values to H0 selectively according to which elements in t are <= 4.
You need to proceed by using a for loop, or by putting the code into a function and using arrayfun so that you never pass in a non-scalar value. Or you need to learn how to use logical indexing. https://www.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html
댓글 수: 0
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!