Reputation: 61
i'd like to Write a function that receives a 2x1 matrix cointaining the x and y.(no scalar inputs) is it possible? I tried as below:
function [d] = dist(A,B)
d=sqrt(((A(1)-B(1))^2+(A(2)-B(2))^2));
end
A and B are 2*1 matrices . how to put vector as function's input??
Upvotes: 0
Views: 28731
Reputation: 45752
I have a different interpretation of your question, I think you're asking how to make your function output all the distances for two lists of (x,y) coords? If so then like this:
function [d] = Dist(A,B)
d=sqrt(((A(:,1)-B(:,1)).^2+(A(:,2)-B(:,2)).^2));
end
So you need to change your ^
from a matrix operation to an elementwise vector operation .^
and then you need to access the first column but ALL the rows i.e. (1,:)
e.g.
A = [0,0;
0,1;
1,1]
B = [1,1;
1,1;
1,1]
Dist(A,B)
ans =
1.41421
1.00000
0.00000
By the way you could neaten up this function like this and still get the same result:
function [d] = Dist(A,B)
d=sqrt(sum((A-B).^2,2));
end
Upvotes: 1
Reputation: 46375
If you want to pass two vectors (since you have A and B each having two elements) as a single parameter, you can either create a 2x2 matrix or a 4x1 vector to pass in. Or you can decide to pass in a cell array (which gives you a bit more flexibility). Example:
A = [1 2];
B = [4 5];
C = [A; B];
d = myDistance(C);
function m = myDistance(x)
dxy = diff(x); % do both x(2,1) - x(1,1) and x(2,2) - x(1,2) in one operation
m = sqrt(sum(dxy.^2));
Alternatively, passing A
and B
as two separate parameters (which makes a lot of sense from readability) should work in the way you described in your question...
Upvotes: 1