필터 지우기
필터 지우기

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