IF not working with vector
4 ビュー (過去 30 日間)
古いコメントを表示
Hello, sorry for the trivial question.
I wrote this function:
function f = g(m)
%piecewise function evaluation
if m <= 0
f(n) = -2*m;
else
f(n) = 2*m;
end
end
Which actually works when g is given numbers individually
g(2) = 2, g(-2) = 2
However when I try to plot it by evaluting the function g in an array of value in x created with linspace it seems to "forget" about if condition in the function statement.
x = linspace(-1,1);
g(x) = "gives a straight line 2x, instead of behaving like abs(2x)"
2 件のコメント
採用された回答
Ameer Hamza
2020 年 4 月 7 日
編集済み: Ameer Hamza
2020 年 4 月 8 日
IIf you want to write your own function with if-else block look to implement abs function, then you will need to write a loop
function f = g(m)
%piecewise function evaluation
for i=1:numel(m)
if m(i) <= 0
f(i) = -2*m(i);
else
f(i) = 2*m(i);
end
end
end
Or a one-liner if your question is specifically related to abs(2*m);
function f = g(m)
f = 2*m.*(m>0) - 2*m.*(m<0);
end
6 件のコメント
Ameer Hamza
2020 年 4 月 8 日
"are your suggestions sort of the only easy ways to do it"
easy is a subjective term. You can say that it requires the least number of statements. Someone might say that following is the "easiest"
function f = g(m)
f = 2*m;
f(f<0) = -f(f<0);
end
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!