How can I make an array of handles?

Hey,
Let's say I have a vector x=[1 2 3 4 5] (I don't know what's in it and the size its size is something I don't know in advance), And I want to make an array of handles which will, let's say, make the following:
f(i) = @(y) 3*x(i)+5*y;
How can I make it? (I'm using Matlab)
This is just a simple function but it will be the same principle I guess.
Thanks!

답변 (3개)

Star Strider
Star Strider 2017년 11월 15일

1 개 추천

Using bsxfun:
f = @(x,y) 3*x + 5*y; % ‘Parent’ Function
ary = @(x,y) bsxfun(f, x(:), y(:)'); % Create Virtual Function Array
x = [1 2 3 4 5]; % ‘x’ — Can Be Anything
y = randi(9, 1, 3); % ‘y’ — Can Be Anything
Result = ary(x, y); % Example Use
the cyclist
the cyclist 2017년 11월 15일
편집: the cyclist 2017년 11월 15일

0 개 추천

Use a cell array:
x = [3 4 5];
i = 2;
f{i} = @(y) 3*x(i)+5*y;
Notice the curly brackets on the left-hand side of the assignment.

댓글 수: 1

Roy Elbaz
Roy Elbaz 2017년 11월 15일
Ok thanks. Is there a way to do it in one action instead of going over all of x components? And if now, is there a way to pre-define the array so I won't enlarge it in every 'for' interval?

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

Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan 2017년 11월 15일

0 개 추천

You don't need an array of handles to do that. You can use arrayfun like this:
x = 1:5;
y = 5;
z = arrayfun(@(x,y) 3*x + 5*y, x(:), repmat(y,length(x),1));

카테고리

도움말 센터File Exchange에서 Structures에 대해 자세히 알아보기

태그

질문:

2017년 11월 15일

답변:

2017년 11월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by