Matlab 3 (function and structure)

% for i = 1 : 10
%     x = linspace(0, 10, 101);
%     plot(x, sin(x+i));
%     print(gcf, '-deps', strcat('plot', num2str(i), '.ps'));
% end


% structure: if else
a = 3;
if rem(a, 2) == 0
    disp('a is even');
else
    disp('a is odd');
end


% structure: switch case
input_num = 1;
switch input_num
    case -1
        disp('negative -1');
    case 0
        disp('zero');
    case 1
        disp('positive 1');
    otherwise
        disp('other value');
end


% structure: while
n=1;
while prod(1:n) < 1e100    % prod(1:n) 从1乘到n,也就是n的阶乘(n!)。1e100是1*10^100
    n = n+1;
end


% test while
% 1+2+3+...+999  summation
sum = 0;
n = 1;
while n <= 999
    sum = sum + n;
    n = n + 1;
end
    

% test for
clear a;
m = 1;
for n = 1:2:10
    a(m) = 2^n;
    m = m + 1;
end
disp(a)




% 没有预先开辟空间,程序每次写入都会去重新开辟A,很占用CPU时间
tic
for ii = 1:2000
    for jj = 1:2000
        A(ii, jj) = ii + jj;
    end
end
toc

% 有预开辟空间,程序不用每次写入A都重新开辟
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



% copy A to B
A = [0 -1 4;
    9 -14 25;
    -34 49 64];
for ii = 1 : size(A, 1)
    for jj = 1 : size(A, 2)
        B(ii, jj) = A(ii, jj);
    end
end
disp(B);

% change the negative entries in B
for ii = 1 : size(B, 1)
    for jj = 1 : size(B, 2)
        if B(ii, jj)<0
            B(ii, jj) = -B(ii, jj);
        end
    end
end
disp(B);



% 打开 mean.m  (build-in function平均数的文件) 命令:
% edit(which('mean.m'))



% 调用自定义Function: freebody 自由落体
d_freebody([0 1], [0 1], [10, 20])


% 调用自定义Function: acc 加速度与力
[acc, force] = e_acc(20, 10, 5, 4, 1)


% 调用自定义Function: F2C 华氏转摄氏
f_F2C();

function d_freebody:

% 自由落体
function [x] = d_freebody(x0, v0, t)
x = x0 + v0.*t + 1/2*9.8*t.*t;  %因为三个参数都可能是Vector(一组数据),所以用点乘,可以计算出很多组结果
end

function e_acc:

function [a, F] = e_acc(v2, v1, t2, t1, m)
a = (v2-v1)./(t2-t1);  % 加速度a=(△v)/(△t)
F = m.*a;              % 所用力F=质量*加速度
end

function f_F2C:

% 华氏转摄氏
function [] = f_F2C()
while true
    F = input('Temperature in F: ');   % 一直让你输入 华氏温度
    if isempty(F)
        break
    end
    C = (F-32)*(5/9);   % 转为 摄氏温度
    disp(strcat('==> Temperature in C = ',num2str(C)));
end
end

functionHandle.m

f = @(x)exp(-2*x);
x = 0 : 0.1 : 2;
plot(x, f(x));
structure.png
logical operator.png
remainder 余数.png
pre allocated.png
break.png
ellipsis...换行 control+c结束执行.png
open build-in functions.png
动态获取传进来的实参的个数与长度.png
function hanldle.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容