anon01
anon01

Reputation: 11181

create matrix function of vector input variable (Matlab)

I'm having trouble creating a function that does what I want. I'm trying to create an anonymous function that, on accepting a vector of length N produces an NxN matrix. I'd like to populate each element of the matrix (ie, with a loop). A short example to be more specific:

N = 2;
Qjk = @(x,y) x * y;

for j = 1:N
  for k = 1:N

     Q(j,k) =@(x) Qjk(x(k),rand);

  end
end

In the end this should produce, eg.:

Q = @(x) [.23*x(1), .16*x(2); .95*x(1), .62*x(2)]

I can write the final expression above by hand and it works as required, but I'm unable to automate this process with a loop/vectorization. Thanks.

Upvotes: 0

Views: 158

Answers (1)

rayryeng
rayryeng

Reputation: 104555

So it is my understanding that you want to create a N x N matrix of elements where the input is a vector of length N?... and more specifically, you wish to take each element in the input vector x and generate a new 1 x N vector where each element in x gets scaled by this new 1 x N vector?

You can avoid loops by using bsxfun:

Q = bsxfun(@times, x(:).', rand(numel(x)));

I'm not sure what shape x is, whether it's a row or column vector but I'm not going to make any assumptions. x(:).' will ensure that your vector becomes a row vector. However, if you want to get your code working as it, get rid of the anonymous function declaration within the actual loop itself. Also, you'll probably want to call Qjk as that is the function you declared, not Q as that is the matrix you are trying to populate.

Simply do:

N = 2;
Q = zeros(N); % New - Allocate to be more efficient
Qjk = @(x,y) x * y;

for j = 1:N
  for k = 1:N

     Q(j,k) = Qjk(x(k),rand); % Change

  end
end

Upvotes: 1

Related Questions