Study notes-Matlab grammar learning

input Output

Use input to get keyboard input:

str=input('Please enter your content')

Use disp to print content to the screen:

disp(['This is your content', num2str(s)])

>> s=input('请输入您的内容')
请输入您的内容22

s =

    22

>> s=input('请输入您的内容:')
请输入您的内容:22

s =

    22

>> disp(['这是您的内容',num2str(s)])
这是您的内容22

Use the fprintf command to format content with quotes: similar to the c language

fprintf('Your score is:%.2f',score)% means to keep two decimal places for printing

fprintf('Your score is:%.2e',score)% means to keep two decimal places and print according to scientific notation

Saving and loading of variables:

>> Data=randn(10)
>> save('data.mat','Data')

>> load data.mat  或者>> load('data.mat')

The fopen function manipulates file objects

r: read mode; w: write mode; a: append mode; r+: read and write mode; w+: create mode to read and write; a+: append mode

>> fp=fopen('test.txt','a+');
>> fprintf(fp,'this is a test string.');
>> fclose(fp);

这样就创建了一个test文件,并在文件内写入了this is a test string.

logic operation

Relational operators: <, >, >=, <=, ==, ~=, true is 1, false is 0

Logical operators: and or not, &, |, ~, and, or, not

Built-in logic operation functions

any(A): Returns True if any element in the vector is non-zero, and the matrix is ​​judged based on the column

xor: XOR

all: true when all elements are non-zero

find(A>b): Find out where the matrix is ​​satisfying the conditional elements

>> N=[1 2 3 0;0 0 0 0;-1 -2 -3 0]

N =

     1     2     3     0
     0     0     0     0
    -1    -2    -3     0

>> find(N>0)

ans =

     1
     4
     7

Conditional structure

function z=f(x,y)
    if x>0 && y>0
        z=x+y;
    elseif x>0 && y<=0
        z=x+y.^2;
    elseif x<=0 && y>0
        z=x.^2+y;
    else
        z=x.^2+y.^2;
    end
end

for loop structure

Taylor expansion of e^x

function y=new_exp(x)
    n=100;
    y=1;
    for i=1:n
       y=y+x^i/factorial(i); 
    end
end

%%factorial(i); 表示i的阶乘

while loop structure

Taylor expansion of e^x

function [n,y]=new2_exp(x)
    diff=0.001;
    y=1;
    n=0;
    while abs(exp(x)-y)>diff
        n=n+1;
        y=y+x^n/factorial(n);
    end
end

 

 

Guess you like

Origin blog.csdn.net/seek97/article/details/108284069