How to get a matrix as an output in a function?
Show older comments
I have been trying to understand how to write this function, but I can't seem to think how. The function is to prompt the user for x1, x2, y1 and y2 coordinates for 5 line segments. Basically, there are 4 input values for each of the 5 line segments. And the output has to be a 5 by 4 matrix, including all the 4 values for each line segment).
function [matrix] = getCoords(x1, x2, y1, y2);
matrix = input('what are the coordinates?');
end
but my function is not working. I would appreciate any kind of help. Thanks in advance.
Answers (1)
Birdman
on 14 Apr 2018
Firstly, it does not make any sense to pass input arguments to your function and not using them in your function and since the only detail you give is that you want to form the output as a 5x4 matrix, the following example might help you. But remember, it is up to you to improve it. I can not say anything else considering the explanation of yours.
function matrix = getCoords(x1, x2, y1, y2)
matrix = repmat([x1 x2 y1 y2],5,1);
end
and when you call your function like
y=getCoords(1,2,3,4)
you will get
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
4 Comments
Yasmin Touly
on 14 Apr 2018
Then, carefully form your inputs:
function matrix = getCoords(x1, x2, y1, y2)
matrix = [x1 x2 y1 y2];
end
and
%demo inputs
x1=[1 2 3 4].';
x2=[5 6 7 8].';
y1=[1 3 5 7].';
y2=[2 4 6 8].';
y=getCoords(x1,x2,y1,y2)
where each column will represent x1,x2,y1 and y2 respectively.
+1 I like the clear explanation in your answer. Note that column vectors can be defined directly, without requiring transpose:
x1 = [1;2;3;4];
Birdman
on 14 Apr 2018
Exactly, thank you. Just a habit for me to define them as row vectors and then taking transpose.
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!