matlab study notes 13_1 function return values

Learn together matlab-matlab function study notes 13

13_1 function return value

Find useful, welcome to discuss mutual learning together - Follow Me

Reference
https://blog.csdn.net/qq_36556893/article/details/79323389#commentBox
https://blog.csdn.net/qq_36556893/article/details/79326325

The function returns a value

  • The return value does not have to use the return statement, but need to return directly to the variable or function matrix written on the back
  • Return Value function / Matrix = The function returns the file name (parameter 1, parameter 2, 3 ... Parameter Parameter n)
function x=init_x(x,m,n)

for i=1:m
    for j=1:n
        x(i,j)=randsample(20,1);
    end
end
  • This example represents the incoming x x, m, n by the values ​​of the parameters, and then return after the change

    Examples

  • Now xx matrix elements need to be assigned to a completely new matrix yy, i.e. replication, specific code as follows:

    The main function execute_1.m

clc
clear
%定义xx,yy矩阵大小
m=3;
n=1;
xx=zeros(m,n);
yy=zeros(m,n);
%初始化xx
xx=init_x(xx,m,n);
%将xx矩阵赋值给yy
yy=function_1(xx,yy,m,n

Xx initialization function init_x.m

function x=init_x(x,m,n)

for i=1:m
    for j=1:n
        x(i,j)=randsample(20,1);
    end
end

Mutator function_1.m

function y=function_1(x,y,m,n)

for i=1:m
    for j=1:n
        y(i,j)=x(i,j);
    end
end

Screenshot results

A plurality of function return value

  • function [Return value 1/1 returns a matrix, returns the value 2/2 returns a matrix, ..., return value n / return matrix n] = the function of the file name (parameter 1, parameter 2, ..., parameter n)

    Examples

  • Xx yy matrix and the matrix elements of the entire exchange, and a new matrix is ​​obtained both after adding zz

    The main function execute_2.m

clc
clear
%定义xx,yy,zz矩阵大小
m=3;
n=1;
xx=zeros(m,n);
yy=zeros(m,n);
zz=zeros(m,n);
%初始化xx,yy
xx=init_x(xx,m,n)
yy=init_y(yy,m,n)
%交换xx矩阵和yy矩阵的元素,并求出xx和yy相加的新矩阵zz
[xx,yy,zz]=function_2(xx,yy,zz,m,n)

Init_x.m initialization function of xx and yy, init_y.m

function x=init_x(x,m,n)

for i=1:m
    for j=1:n
        x(i,j)=randsample(20,1);
    end
end

function y=init_y(y,m,n)

for i=1:m
    for j=1:n
        y(i,j)=randsample(20,1);
    end
end

Switching matrix elements and an adding function function_2.m

function [x,y,z]=function_2(x,y,z,m,n)
tempx=x;%中间变量
%x和y交换
for i=1:m
    for j=1:n
        x(i,j)=y(i,j);
        y(i,j)=tempx(i,j);
    end
end

%x加上y
for i=1:m
    for j=1:n
        z(i,j)=x(i,j)+y(i,j);
    end
end

Here Insert Picture Description

Guess you like

Origin www.cnblogs.com/cloud-ken/p/11786023.html