Reputation: 11
Here is my code that i tried to write a matlab function that takes a matrix as input and returned a matrix as output.
a=[ 1 2 3; 4 5 6; 7 8 9];
function [s]= try_1(a)
%takes a matrix as a input
display(' data matrix');
disp(a);
disp('dimension of the matrix');
[m n]= size(a); %calculate the dimension of data matrix
s = mean(a);
end
Upvotes: 0
Views: 105
Reputation: 396
Explain clearly where you execute the above code ? if you execute in command prompt don't use function. code likes this
a=[ 1 2 3; 4 5 6; 7 8 9];
%takes a matrix as a input
display(' data matrix');
disp(a);
disp('dimension of the matrix');
[m n]= size(a); %calculate the dimension of data matrix
s = mean(a);
or if you are not using command prompt then put the value "a" in another function and call the try_1 function from new function you created. code like this
function parent()
a=[ 1 2 3; 4 5 6; 7 8 9];
s= try_1(a)
end
function [s]= try_1(a)
%takes a matrix as a input
display(' data matrix');
disp(a);
disp('dimension of the matrix');
[m n]= size(a); %calculate the dimension of data matrix
s = mean(a);
end
or assign then value inside the try_1 function . code like this
function [s]= try_1(a)
a=[ 1 2 3; 4 5 6; 7 8 9];
%takes a matrix as a input
display(' data matrix');
disp(a);
disp('dimension of the matrix');
[m n]= size(a); %calculate the dimension of data matrix
s = mean(a);
end
Upvotes: 0
Reputation: 14316
You cannnot define a function inside a script. MATLAB assumes your file is a script, because it starts with a=[ 1 2 3; 4 5 6; 7 8 9];
- i.e. by defining a variable. MATLAB thus assumes a series of instructions is following and throws an error when it sees the function definition.
You also have to distinguish function definitions and function calls. With your code above, i.e.
function s = try_1(a)
...
end
you define what the function does (function definition), but you do not call it yet, i.e. nothing happens. For something to happen, you will have to call it by
a=[ 1 2 3; 4 5 6; 7 8 9];
s = try_1(a);
in a script or in the workspace.
About file names and what to put in each file: Functions are identified by their filename in MATLAB. It is absolutely necessary to have the function try_1()
in a file called try_1.m
. And this file can not contain anything else. The a=[ 1 2 3; 4 5 6; 7 8 9];
and function calls belong in a separate script (or to test the behavior simply type it in the command window).
Upvotes: 3