1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > matlab学习笔记(2)——台大郭彦甫版

matlab学习笔记(2)——台大郭彦甫版

时间:2021-02-07 21:43:10

相关推荐

matlab学习笔记(2)——台大郭彦甫版

Structure Programming

Logical Operators

1. if语句

%% if elseif elsea = 3;if rem(a,2) == 0disp('a is even.');elsedisp('a is odd.');end

2. switch语句

%% switchinput_num = 1;switch input_numcase -1disp('negative 1');case 0disp('zero');case 1disp('positive 1');otherwisedisp('other value');end

3. while语句

%% whilen = 1;while prod(1:n) < 1e100%prod 连乘n = n+1;end

%% Exercisesum = 0;i = 0;while i < 999i = i + 1;sum = sum + i;end

4. for语句

%% forfor x = 1:10a(x) = 2^x;enddisp(a);for y = 1:2:10b(y) = 2^y;enddisp(b);for z = 1:2:10c(z) = 2^z;disp(c(z));end

5. 预分配内存

%% pre-allocating space%% program Aticfor ii = 1:2000for jj = 1:2000A(ii,jj) = ii + jj;endendtoc%% program BticA = zeros(2000,2000);for ii = 1:size(A,1)for jj = 1:size(A,2)A(ii,jj) = ii + jj;endendtoc

Exercise

%% Exerciseclear all;clc;A = [0 -1 4; 9 -14 25;-34 49 64];B = zeros(3,3);for ii = 1:size(A,1)for jj = 1:size(A,2)B(ii,jj) = abs(A(ii,jj));endenddisp(B);

6.break

%% breakclear all;clc;x = 2; k = 0; error = inf;error_threshold = 1e-32;while error > error_thresholdif k > 100breakendx = x - sin(x)/cos(x);error = abs(x-pi);k = k + 1;end

小技巧

1. clear all、close all、clc

2.使用分号(;)

3.使用换行号(...)

Function

来源:MATLAB02:结构化编程和函数定义_ncepu_Chen的博客-CSDN博客

自定函数

%% user define functionsfunction x = freebody(x0,v0,t)% calculation of free falling% x0: initial displacement i m% v0: initial velocity in m/sec% t: the elapsed time in sec% x: the depth of falling in mx = x0 + v0.*t + 1/2*9.8*t.*t; % t采用点乘,让多组数据可同时计算>> freebody(0,0,10)ans =490 >> freebody([0 1],[0 1],[10 20])ans =490 1981

%% functions with multiple inputs and outputsfunction [a,F] = acc(v2,v1,t2,t1,m)a = (v2 - v1)./(t2 - t1);F = m.*a;>> [Acc Force] = acc(20,10,5,4,1)Acc =10 Force =10

Exercise

%% Fahrenheit degrees to Celsius degreesfunction F2Cwhile 1 % 这是一个无限循环,它会一直执行下去,% 直到遇到 break 语句才会退出循环。F_degree = input('Tempreature in F:','s'); % 这行代码从用户处获取输入,要求用户输入一个华氏度的温度值,% 并将其存储在 F_degree 变量中。'Tempreature in F:' 是输入提示文本。F_degree = str2num(F_degree); % 这行代码将用户输入的温度值(字符串类型)转换为数值类型,% 并将结果存储回 F_degree 变量中。if isempty(F_degree)breakend%这个条件语句检查 F_degree 是否为空。% 如果用户没有输入任何内容,那么 F_degree 将为空,这时会执行 break 语句,退出循环。C_degree = (F_degree - 32).*5/9;disp(['Tempreature in Celsius:' num2str(C_degree)])% 这行代码使用 disp 函数在命令窗口中显示转换后的摄氏度值。% 它将摄氏度值转换为字符串,然后与前缀文本 'Tempreature in Celsius:' 连接起来进行显示。end

MATLAB02:结构化编程和函数定义_ncepu_Chen的博客-CSDN博客

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。