How can I use a function on a series of values?

3 ビュー (過去 30 日間)
Nishant Singhal
Nishant Singhal 2016 年 12 月 10 日
回答済み: Walter Roberson 2016 年 12 月 10 日
So I've got a function y=f(x), where y=roots([1 0 x]).
I have a matrix n, which is:
-1 0 0
-2 0 0
-3 0 0
-4 0 0
-5 0 0
-6 0 0
-7 0 0
-8 0 0
-9 0 0
-10 0 0
I'm trying to have columns 2 and 3 be the solutions to the function.
Here's what I tried:
>> n(:,2:3)=f(n(:,1))
It keeps saying 'error using horzcat'.
But if I do it manually, one by one, it works, for example:
>> n(1,2:3)=f(n(1,1))
This would make row 1 of n (-1, -1, 1), which is correct.
How can I make it work for all of the rows at once?

回答 (2 件)

David Barry
David Barry 2016 年 12 月 10 日
a = arrayfun(f, n(:,1), 'UniformOutput', false);
n(:,2:3) = [a{:}]';

Walter Roberson
Walter Roberson 2016 年 12 月 10 日
You cannot. roots() only works with one row at a time.
However, you are working with a simple quadratic so you can easily construct the quadratic solution formula and vectorize that. A moment of thought shows that the solutions will be +/- sqrt(-x)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by