フィルターのクリア

apply a function to vector

1 回表示 (過去 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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by