matlab definition function
Syntax: function [output] = functionName(input)
例: function [output1, output2] = velocity(v0, a, t0)
There is no need to use [] when there is only one output.
Example: function out = add(a, b);
Requirement: The file name of matlab needs to be the same as the function name before it can run, and there is only one function in a file.
There are multiple functions in one .m file
The definition of the function is consistent with the above
It should be noted that there is one more main function and several slave functions, and the function ends with end, such as the following code:
%% 主函数
function optimise()
clear
close all
% 下面定义的函数可以在这里调用
readFile(filename, dataline);
writeFile(filename, R0, L0);
% 注意
end
%% 读取文件函数
function data = readFile(filename, dataline)
fid = fopen(filename); % 文件名
lines= textscan(fid,'%f %[^\n]',1,'Headerlines',dataline-1); % 跳过2读下面的1行,修改读取格式即可获取浮点类型的数据
data = lines{1};
end
%% 参数写入函数
function [] = writeFile(filename, R0, L0)
% 打开文件进行写操作
fid = fopen(filename, 'w');
% 写入数据
fprintf(fid, '*SET,R0,%f\n*SET,L0,%f\n', R0, L0);
% 关闭文件
fclose(fid);
end
The file name of matlab needs to be consistent with the name of the main function before the program can run.
Define a function that returns nothing
Two ways of writing:
function [] = add()
function add()