Basic question about loops
显示 更早的评论
Very basic question: why is this not working?
instead of
Idx2=Idx(:,2)
Idx3=Idx(:,3)
Idx4=Idx(:,4)
Idx5=Idx(:,5)
I wrote
for i=2:5
Idx(i)=Idx(:,i)
end
The error is: Unable to perform assignment because the left and right sides have a different number of elements.
10 个评论
millercommamatt
2021-10-29
Let me make sure I understand what you are trying to achieve.
You want to break out each column - or some subset of columns - of a 2-D array into their own variables?
"Very basic question: why is this not working?"
Because you chose a complex and indirect way to write your code.
Numbering variables like that is a sign that you are doing something wrong.
Forcing meta-data (e.g. pseudo-indices) into variable names is one way that beginners force themselves into writing slow, complex, inefficient, obfuscated, buggy code that is difficult to debug.
Your task could be solved simply and much more efficiently using indexing.
Pelajar UM
2021-10-29
Stephen23
2021-10-29
"but can't quite understand how indexing works. "
You are using indexing already on the RHS. That is how indexing works.
Splitting the data up into numbered variables is most likely a superfluous step: why can't you just access the data using that indexing? Or if splitting is required, just use a cell array (e.g. via NUM2CELL) rather than lots of variables.
Pelajar UM
2021-10-30
"...how do I output the results to a single array?"
Use indexing on the LHS, just like you are already doing on the RHS.
Preallocate the ND array using nan(..) and then index into it. If the number of elements returned on each iteration are different then you will have to use a cell array instead:
Pelajar UM
2021-10-30
编辑:Pelajar UM
2021-10-30
The size of each RHS depends on the indices, which you have told us nothing about. So I can only presume that they are different on each iteration. In that case, you could use a cell array:
C = cell(1,10);
for k = 2:10
C{k} = centroid(Idx(:,k),:);
end
Pelajar UM
2021-10-30
编辑:Pelajar UM
2021-10-31
Stephen23
2021-10-31
"Small error: your code mixes k and i"
Fixed, thank you!
If the content of C are of suitable sizes then after the loop you could concatenate them back into one array, e.g.:
A = cat(3,C{:})
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!