for loop value array must be a row vector(?)

4 次查看(过去 30 天)
Hi all,
The next-to-simplest matlab code is approximately:
idxs = [1,2,3];
for k = idxs
k
end
k = 1
k = 2
k = 3
But if the idxs array is a column vector, the results are rather different:
idxs = [1;2;3];
for k = idxs
k
end
k = 3×1
1 2 3
That is, you get one value of k equal to the whole column vector. I did not know that. I've been using Matlab for almost 30 years. How did I miss that?
  2 个评论
Stephen23
Stephen23 2023-5-17
编辑:Stephen23 2023-5-17
This is an ancient MATLAB feature that no one uses, no one likes, and only causes bugs:
I for one would love to be able to write:
for k = find(..)
without the ugly rigmarole and obfuscation that is currently required.
No doubt some at TMW worry about "breaking existing code", but that argument does not hold much water:
  • no one uses this syntax
  • it causes far more bugs than it being used as intended,
  • TMW have broken other fairly fundamental syntaxes (e.g. input/output argument order of some basic functions, changed default first/last value returned, changes to scoping rules, etc. etc.) without causing the end of the world.
Just like IF accepting non-scalar values, this is something that should have been retired a long time ago.
Walter Roberson
Walter Roberson 2023-5-17
I have occasionally taken advantage of this aspect of for. Not very much at all.

请先登录,再进行评论。

采纳的回答

Cris LaPierre
Cris LaPierre 2023-5-17
移动:Matt J 2023-5-18
I didn't realize that either. It does appear to be documented.
  • valArray — Create a column vector, index, from subsequent columns of array valArray on each iteration. For example, on the first iteration, index = valArray(:,1). The loop executes a maximum of n times, where n is the number of columns of valArray, given by numel(valArray(1,:)). The input valArray can be of any MATLAB® data type, including a character vector, cell array, or struct.
So it is the number of columns that determines how many times your loop runs, and index is all values in the nth column.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

标签

产品


版本

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by