Matlab – Calling functions & scripts in Matlab/Octave

MATLABoctave

How do call a script to a function and vica versa in Matlab/Octave?

function mean_DNA_Microarray = Calc_mean_DNA_Microarray(M)
   M = DNA_Microarray 
   mean_DNA_Microarray = M - ones(5,25)*mean(M(:,25)) 
end 

The response is

error: invalid call to script
C:\Users\Nacho\Documents\Matlab\DNA_Microarray.m error: called from:
error: C:\Users\Nacho\Documents\Matlab\Calc_mean_DNA_Microarray.m at
line 3, column 3

Now this will work if I call DNA_Microarray a function, but the problem requires that it remain as a script.

Best Answer

First of all, you are not defining your function correctly, as the function does not know what M is (unless it is a global vairable, but I doubt so).

In ANY programming language, you need to tell a function which variables it is going to work with. This is not Matlab specific. In Matlab you will do it so:

function mean_DNA_Microarray = Calc_mean_DNA_Microarray(M)  % Look! we are telling him what M is!
    mean_DNA_Microarray = M - ones(5,25)*mean(M(:,25)) 
end

Then you want to all the function from somewhere else you would need to just type its name and pass in the arguments, in this case what inside the function is going to be called M

clear;
clc;
% Test code
Mnameoutofthefunction=rand(100,100);
DNAmean = DNA_Microarray(Mnameoutofthefunction); % here we are calling it!

Remember to save the function as functionname.m , in your case DNA_Microarray.m , else Matlab wont know which one it is.

But I HIGHLY recommend you to read a book about Matlab or just about programming in general, as it seems like you could benefit from some basic introduction.

Following @am304 suggestion, here you can find nice tutorials:

http://www.mathworks.co.uk/academia/student_center/tutorials/

EDIT What you want to do is create a function as follows:

function mean_DNA_Microarray = Calc_mean_DNA_Microarray(M)  % Look! we are telling him what M is!
    mean_DNA_Microarray = M - ones(5,25)*mean(M(:,25)) 
end

And then, inside your function DNA_Microarray call Calc_mean_DNA_Microarray with the input M

Related Topic