vectorization of piecewise defined function

2 ビュー (過去 30 日間)
Charles Miller
Charles Miller 2016 年 5 月 30 日
コメント済み: dpb 2016 年 5 月 31 日
need to calculate output of
f(x)={3x^2+5, x<0 [and]
-3x^2+5, x>=0}
using vectorization and one output vector and cannot figure out. it is for a class assignment and I know it can easily be done with loops and conditional statements, but part of my lab requires it being calculated using vectorization with only one output vector. needs to be done on domain -9<=x<=9. input vector is not the problem, its calculating the piecewise defined output. please help!

回答 (3 件)

Walter Roberson
Walter Roberson 2016 年 5 月 31 日
-sign(x) .* 3 .* x.^2 + 5
  1 件のコメント
dpb
dpb 2016 年 5 月 31 日
Good catch on the specific formulation, Walter! :)

サインインしてコメントする。


dpb
dpb 2016 年 5 月 30 日
Well, as homework it's not kosher to just provide the solution; that does you no good in learning...
HINT: type
doc 'logical indexing' % at command line and see if doesn't lead you to some useful information
  1 件のコメント
Charles Miller
Charles Miller 2016 年 5 月 31 日
thank you!

サインインしてコメントする。


Star Strider
Star Strider 2016 年 5 月 30 日
You came very close with your own code. I added a couple multiplication operators and a couple piece-wise multiplication operators to your code to get this:
f = @(x) (3*x.^2+5).*(x<0) + (-3*x.^2+5).*(x>=0);
t = linspace(-5, 5);
figure(1)
plot(t, f(t))
grid
The code works by creating a logical vector with the logical tests that are true or 1 where the test is true, and false or 0 elsewhere for each test and so for each calculation as well. These logical values are converted to their numerical equivalents when you use them in calculations.
See the documentation for Array vs. Matrix Operations for details on piece-wise operators.
  2 件のコメント
Charles Miller
Charles Miller 2016 年 5 月 31 日
thank you!
Star Strider
Star Strider 2016 年 5 月 31 日
My pleasure!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeAssumptions についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by