Matlab之for、if、while

您所在的位置:网站首页 matlab里的while循环语句 Matlab之for、if、while

Matlab之for、if、while

#Matlab之for、if、while| 来源: 网络整理| 查看: 265

Matlab用法之for、if、while 最近在用matlab写代码,所以随手写。

for语句

语法

for index = values statements end

例子

以 -0.2 为步长递增,并显示值。 for v = 1.0:-0.2:0.0 disp(v) end 执行指定值的语句 for v = [1 5 8 17] disp(v) end 对每个矩阵列重复执行语句 for I = eye(4,3) disp('Current unit vector:') disp(I) end 分配矩阵值 创建一个 10 阶 Hilbert 矩阵。 s = 10; H = zeros(s); for c = 1:s for r = 1:s H(r,c) = 1/(r+c-1); end end if语句

语法

if expression statements elseif expression statements else statements end

例子

使用 if、elseif 和 else 指定条件 创建一个由 1 组成的矩阵。 nrows = 4; ncols = 6; A = ones(nrows,ncols); 遍历矩阵并为每个元素指定一个新值。对主对角线赋值 2,对相邻对角线赋值 -1,对其他位置赋值 0。 for c = 1:ncols for r = 1:nrows if r == c A(r,c) = 2; elseif abs(r-c) == 1 A(r,c) = -1; else A(r,c) = 0; end end end A 比较数组 在数组中包含关系运算符的表达式(例如 A > 0)仅在结果中的每个元素都为非零时才为 true。 使用 any 函数测试任何结果是否为 true。 limit = 0.75; A = rand(10,1) A = 10×1 0.8147 0.9058 0.1270 0.9134 0.6324 0.0975 0.2785 0.5469 0.9575 0.9649 if any(A > limit) disp('There is at least one value above the limit.') else disp('All values are below the limit.') end 测试数组的相等性 使用 isequal 而不是 == 运算符比较数组来测试相等性,因为当数组的大小不同时 == 会导致错误。 创建两个数组。 A = ones(2,3); B = rand(3,4,5); 如果 size(A) 与 size(B) 相同,则会串联这两个数组;否则显示一条警告并返回一个空数组。 if isequal(size(A),size(B)) C = [A; B]; else disp('A and B are not the same size.') C = []; end 比较字符向量 使用 strcmp 比较字符向量。当字符向量的大小不同时,使用 == 测试相等性会产生错误。 reply = input('Would you like to see an echo? (y/n): ','s'); if strcmp(reply,'y') disp(reply) end 评估表达式中的多个条件 确定值是否在指定范围内。 x = 10; minVal = 2; maxVal = 6; if (x >= minVal) && (x maxVal) disp('Value exceeds maximum value.') else disp('Value is below minimum value.') end while语句

语法

while expression statements end

例子

重复执行语句,直到表达式为 False 使用 while 循环计算 factorial(10)。 n = 10; f = n; while n > 1 n = n-1; f = f*n; end disp(['n! = ' num2str(f)]) 跳至下一循环迭代 统计文件 magic.m 中的代码行数。使用 continue 语句跳过空白行和注释。continue 跳过 while 循环中的其余指令并开始下一迭代。 fid = fopen('magic.m','r'); count = 0; while ~feof(fid) line = fgetl(fid); if isempty(line) || strncmp(line,'%',1) || ~ischar(line) continue end count = count + 1; end count 在表达式为 false 之前退出循环 求随机数序列之和,直到下一随机数大于上限为止。然后,使用 break 语句退出循环。 limit = 0.8; s = 0; while 1 tmp = rand; if tmp > limit break end s = s + tmp; end

总的来说,和C++类似,但是要简单些。 来自:https://ww2.mathworks.cn/help/index.html (好网站)



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3