Matlab使用for语句来编写一定次数的循环

您所在的位置:网站首页 matlabfor循环递减 Matlab使用for语句来编写一定次数的循环

Matlab使用for语句来编写一定次数的循环

2023-04-02 12:19| 来源: 网络整理| 查看: 265

文章目录

展开 常见用法语法说明分配矩阵值递减值执行指定值的语句对每个矩阵列重复执行语句友情提示 4.6 (5)

今天,来教大家Matlab中for语句的使用。for用于编写循环语句,虽然实际编程或数据处理中,要尽量避免for循环的使用。for循环指的是,从指定数组元素开始到某指定数组元素结束,一直执行某条语句。当然,我们可以使用break打断循环,也可以使用continue跳过循环中的余下指令,继续下一次循环。

Matlab使用for语句来编写一定次数的循环

本文,主要讲解Matlab中for语句的常见用法、语法说明、分配矩阵值、递减值、执行指定值的语句、对每个矩阵列重复执行语句。

下面,我们首先给出Matlab中关于for函数的帮助文档:

>> help for for Repeat statements a specific number of times. The general form of a for statement is: for variable = expr, statement, ..., statement END The columns of the expression are stored one at a time in the variable and then the following statements, up to the END, are executed. The expression is often of the form X:Y, in which case its columns are simply scalars. Some examples (assume N has already been assigned a value). for R = 1:N for C = 1:N A(R,C) = 1/(R+C-1); end end Step S with increments of -0.1 for S = 1.0: -0.1: 0.0, do_some_task(S), end Set E to the unit N-vectors for E = eye(N), do_some_task(E), end Long loops are more memory efficient when the colon expression appears in the for statement since the index vector is never created. The BREAK statement can be used to terminate the loop prematurely.常见用法for index = values statements end语法说明

for index = values, statements, end 在循环中将一组语句执行特定次数。values 为下列形式之一:

initVal:endVal – index 变量从 initVal 至 endVal 按 1 递增,重复执行 statements 直到 index 大于 endVal。

initVal:step:endVal – 每次迭代时按值 step 对 index 进行递增,或在 step 是负数时对 index 进行递减。

valArray – 每次迭代时从数组 valArray 的后续列创建列向量 index。例如,在第一次迭代时,index = valArray(:,1)。循环最多执行 n 次,其中 n 是 valArray 的列数,由 numel(valArray(1,:)) 给定。输入 valArray 可属于任何 MATLAB® 数据类型,包括字符向量、元胞数组或结构体。

分配矩阵值

创建一个 10 阶 Hilbert 矩阵。

s = 10; H = zeros(s); for c = 1:s for r = 1:s H(r,c) = 1/(r+c-1); end end

以上表示c从1到10,r从1到10,H矩阵每个对应元素的值为1/(r+c-1)。最终得到的H矩阵如下图所示:

Matlab使用for语句来编写一定次数的循环递减值

以 -0.2 为步长递增,并显示值。

for v = 1.0:-0.2:0.0 disp(v) end

输出结果为:

1 0.8000 0.6000 0.4000 0.2000 0执行指定值的语句for v = [1 5 8 17] disp(v) end

输出结果为:

1 5 8 17对每个矩阵列重复执行语句for I = eye(4,3) disp('Current unit vector:') disp(I) end

输出结果为:

Current unit vector: 1 0 0 0 Current unit vector: 0 1 0 0 Current unit vector: 0 0 1 0友情提示

基本上,了解了这些for语句的基本语法,你就可以自己写循环,实现自己的目的了,比如在进行数据处理的时候。

最后,需要注意的是,for循环除了end自动退出循环,也可以使用break以及continue。

要以编程方式退出循环,请使用 break 语句。要跳过循环中的其余指令,并开始下一次迭代,请使用 continue 语句。避免在循环语句内对 index 变量赋值。for 语句会覆盖循环中对 index 所做的任何更改。要对单列向量的值进行迭代,首先将其转置,以创建一个行向量。

如果你有任何不懂得地方,都可以向我提问。

共计5人评分,平均4.6分

到目前为止还没有投票~

很抱歉,这篇文章对您没有用!

让我们改善这篇文章!

告诉我们我们如何改善这篇文章?

转载文章,原文出处:MathWorks官网,由古哥整理发布

如若转载,请注明出处:https://iymark.com/articles/2273.html



【本文地址】


今日新闻


推荐新闻


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