apply a function to vector
3 ビュー (過去 30 日間)
古いコメントを表示
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
0 件のコメント
回答 (2 件)
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))
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)
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!