Filter löschen
Filter löschen

apply a function to vector

2 Ansichten (letzte 30 Tage)
Archit
Archit am 16 Apr. 2012
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

Antworten (2)

Walter Roberson
Walter Roberson am 16 Apr. 2012
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 Kommentar
Archit
Archit am 16 Apr. 2012
I am getting this fn from somewhere.. i cannot modify it later on. So i have to do with what i have.

Melden Sie sich an, um zu kommentieren.


Sargondjani
Sargondjani am 16 Apr. 2012
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)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by