How to get a matrix as an output in a function?

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.

답변 (1개)

Birdman
Birdman 2018년 4월 14일

2 개 추천

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

thank u so much. but what if I want different values for all the 4 values in every row?
Birdman
Birdman 2018년 4월 14일
편집: Birdman 2018년 4월 14일
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.
Stephen23
Stephen23 2018년 4월 14일
편집: Stephen23 2018년 4월 14일
+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
Birdman 2018년 4월 14일
Exactly, thank you. Just a habit for me to define them as row vectors and then taking transpose.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

태그

질문:

2018년 4월 14일

편집:

2018년 4월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by