Matlab之for、if、while

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 within specified range.')
elseif (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 (好网站)

### MATLAB 中 `if` 和 `while` 语句的使用 #### 条件判断:`if` 语句 在 MATLAB 中,`if` 语句用于执行基于特定条件的操作。语法如下: ```matlab if condition % 执行某些操作 elseif another_condition % 如果第一个条件不满足,则尝试此条件并执行相应操作 else % 如果以上所有条件都不满足则执行此处代码 end ``` 例如,在检测给定数值是否为正数时可以这样写[^2]: ```matlab value = input('Enter a number: '); if value > 0 disp('The entered number is positive.'); elseif value < 0 disp('The entered number is negative.'); else disp('You have entered zero.'); end ``` 这段程序会提示用户输入一个数字,并根据该值显示相应的消息。 #### 循环控制:`while` 语句 `while` 语句允许重复执行一组命令直到指定条件不再成立为止。其基本结构为: ```matlab while condition % 当条件为真时反复执行这些指令 end ``` 考虑这样一个例子来说明如何利用 `while` 实现累加器功能[^1]: ```matlab sumValue = 0; counter = 1; while counter <= 10 sumValue = sumValue + counter; counter = counter + 1; end disp(['Sum of numbers from 1 to 10 is ', num2str(sumValue)]); ``` 这里定义了一个计数器变量 `counter` 初始设置为 1 ,并通过每次迭代增加它直至达到或超过上限(本例中为 10)。在此过程中不断更新总和 `sumValue` 的值。 另外值得注意的是,当涉及到更复杂的逻辑处理时,还可以结合多个条件以及嵌套不同的流程控制语句一起工作。比如筛选素数的例子展示了 `for` 和 `while` 结合使用的场景[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值