多个循环变量Matlab [英] Multiple loop variables Matlab
问题描述
另外,我非常清楚循环迭代 computations ,所以它会影响速度,因为我已经是一个嵌套在Matlab中的循环。 MATLAB的 支持多个循环变量,因为它支持矩阵作为循环表达式。这是如何运作的? 在每次迭代开始时,矩阵的各个列被分配给循环变量。
示例代码:
V = [1:1:5; 2:2:10]
,iv = V,
fprintf('iv = [%d%d]; \\\
',iv);
end
输出:
V =
1 2 3 4 5
2 4 6 8 10
iv = [1 2];
iv = [2 4];
iv = [3 6];
iv = [4 8];
iv = [5 10];
我们在这里实现了两个循环变量, iv(1) code>和
iv(2)
,它们是用作循环表达式的矩阵的行。请注意,该数组可以是任何类型(例如,字符串,单元格,结构等)。
$ b $ p $摘要
预先定义循环变量的每次迭代,并将它们存储为矩阵的行。 在循环中,循环变量将包含矩阵的一列。
附注
我猜这个惯例是由于 冒号
运算符通过 horizontal 连接产生一个数组而不是垂直的。只要考虑以下情况会发生什么:
对于ii =(1:3)。',numel(ii),end
您可能期待三次迭代,每次迭代表示 numel(ii)= 1
,但是只有一次迭代,循环报告:
ans =
3
如果您期望 ii
是一个标量。
术语
for loop_variable = loop_expression,statement,...,statement end
In C++/C, we have multiple loop variables in a single loop, like for(int i=0; int j=0; i<5; j<5; i++; j++)
Is there any facility in Matlab for multiple variables loop?
And also, I'm very conscious in loop iterations computations, so does it effects the speed as I'v already a nested loop in Matlab.
MATLAB sort of supports multiple loop variables in that it supports a matrix as the loop expression. How does that work? Individual columns of the matrix are assigned to the loop variable at the beginning of each iteration.
Example code:
V = [1:1:5; 2:2:10]
for iv = V,
fprintf('iv = [%d %d];\n',iv);
end
Output:
V =
1 2 3 4 5
2 4 6 8 10
iv = [1 2];
iv = [2 4];
iv = [3 6];
iv = [4 8];
iv = [5 10];
We've achieved two loop variables here, iv(1)
and iv(2)
, which are specified by the rows of the matrix used as the loop expression. Note that the array can be any type (e.g. string, cell, struct, etc.).
Summary
Pre-define each iteration of the loop variables, and store them as the rows of the matrix. Inside the loop, the loop variable will contain a column of the matrix.
Side note
I'm guessing that this convention is a consequence of the fact that the colon
operator produces an array by horizontal concatenation rather than vertical. Just consider what happens in the following case:
for ii = (1:3).', numel(ii), end
You might be expecting three iterations, each indicating numel(ii)=1
, but you only get one iteration and the loop reports:
ans =
3
The problem is clear if you are expecting ii
to be a scalar.
Terminology
for loop_variable = loop_expression, statement, ..., statement end
这篇关于多个循环变量Matlab的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!