How to input a matrix of unknown dimensions into a function?

function avg_vals = function_name(A)
A = %This is where I'm confused
avg_vals = mean(A,2);
end
I'm trying to create a function that will accept a matrix (A) that contains an unspecified number of rows and columns. I want it to then average the rows (rather than columns) and return those values as a column vector. It could be that I'm approaching this from the totally wrong angle, so any advice is welcome.

 채택된 답변

Ahmed A. Selman
Ahmed A. Selman 2013년 4월 10일
A is an input argument passed from function call function_name(A). SO, DELETE THIS LINE from the beginning, you do not need to input A a second time :)
function avg_vals = function_name(A)
A = % and this is where I am truly confused. Delete this line
avg_vals = mean(A,2);
end
When you want to work with this function, use:
ex1.:
A=1:10; % This is a 1-D vector
function_name(A)
ex2.
A=magic(4); % This is a 2-D matrix
function_name(A)

댓글 수: 3

Leah
Leah 2013년 4월 10일
편집: Leah 2013년 4월 10일
I have tried entering values into the function that you suggest above, and it returns an "Unexpected MATLAB expression" error. Is it that I am entering them in the wrong format? In the command window I enter:
function_name(1 2 3; 4 5 6; 7 8 9)
To simulate a matrix that could feasibly be entered, and it returns the error message that I mentioned above.
EDIT: I tried entering in a single value, 1, into the function and it returned 1 as the average value. So it seems that my main issue is that this function will not accept a matrix of any size (nor a row or column vector).
A matrix is entered using the square brackets. So try this instead:
function_name([1 2 3; 4 5 6; 7 8 9])
Everything inside the [...] is treated as a single matrix.
That did the trick!
Thank you for your help!

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

질문:

2013년 4월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by