apply a function to vector

2 次查看(过去 30 天)
Archit
Archit 2012-4-16
I have a function like
fn=@(a) [a(1,:).^2 ; a(2,:).^2 ; 1]
i want to apply it to matrix
w=[2 3 4 5; 1 2 3 4]
but i is giving error CAT dimensions must agree.
i can evaluate it in a loop for every column of 'w'
but since 'fn' has third row as a constant, it cannot extend it to vector
ny idea how to vectorise this fn(w)
or what could i have done had i got a function like
fn=@(a)[a(1)^2;a(2)^2;1]
ie it cannot be vectorized, but i want to evaluate fn for a matrix of size 2xN

回答(2 个)

Walter Roberson
Walter Roberson 2012-4-16
a(1,:)^2 will not generally work. It means a(1,:) * a(1,:) which is matrix multiplication of a 1xN by a 1xN but in matrix multiplication the inner dimensions must agree so a(1,:)^2 can only work if "a" only has a single row. Perhaps you mean .^2 instead of ^2 ?
Anyhow: ones(1, size(a,2))
  1 个评论
Archit
Archit 2012-4-16
I am getting this fn from somewhere.. i cannot modify it later on. So i have to do with what i have.

请先登录,再进行评论。


Sargondjani
Sargondjani 2012-4-16
you can loop for the second equation you gave for fn (the one with ^2):
fn=@(a)[a(1)^2;a(2)^2;1];
w=...
for iw=1:size(w,2));
y(iw)=fn(w(:,iw));
end
this should give you the answer in 3x1 vector. but i would still recommend using the other function (after adjusting it):
fn=@(a) [a(1,:).^2 ; a(2,:).^2 ; ones(1, size(a,2))];
(as Walter suggested)
and then
y=fn(w)
should give the same result (but faster)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by