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

Structure Programming

 Logical Operators

 1. if语句

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

2. switch语句

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

3. while语句

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

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

4. for语句

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

 5. 预分配内存

%% pre-allocating space
%% program A
tic
for ii = 1:2000for jj = 1:2000A(ii,jj) = ii + jj;end
end
toc%% program B
tic
A = zeros(2000,2000);
for ii = 1:size(A,1)for jj = 1:size(A,2)A(ii,jj) = ii + jj;end
end
toc

Exercise

%% Exercise
clear 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));end
end
disp(B);

6.break

%% break
clear 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 m
x = 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 outputs
function [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 degrees
function F2C
while 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博客


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部