vector function takes vector input ?

조회 수: 1 (최근 30일)
Nora Khaled
Nora Khaled 2019년 2월 10일
댓글: Star Strider 2019년 2월 13일
Hello !
I am having truble inserting vectors as an input to a function that is a vector
what I did is
I defined a function as
gradient=@(x) [1;x;x^2;x^3];
then I need to input a vector to it. like this
gradient([2 ;3 ; 4])
or
gradient([2 3 4])
so the result I am hoping for is a matrix where each column represent a function (1,x,x^2,x^3)
and each row is the value of the function at each point in the input vector.
so it would be some thing like:
1 2 4 8
1 3 9 27
1 4 16 46
I have done this using loop. but since the data I am dealing with is large this takes so long and I would brefer a method that does it in a vector form.

채택된 답변

Star Strider
Star Strider 2019년 2월 10일
First, gradient is a quite useful built-in MATLAB function, so name your function something different.
Second, your function needs some help.
Try this:
myGradient = @(x) [ones(size(x(:))), x(:), x(:).^2, x(:).^3];
Y = myGradient([2 3 4])
I will leave it to you to explore the details of colon operator single-indexing (it forces ‘x’ here to be a column vector), and the necessity to use the ones function.
Y =
1 2 4 8
1 3 9 27
1 4 16 64
  댓글 수: 4
Nora Khaled
Nora Khaled 2019년 2월 13일
sorry did not know I had a choice of accepting the answer.
And again, Thank you!
Star Strider
Star Strider 2019년 2월 13일
As always, my pleasure.
Thank you!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by