Basic question about loops
Show older comments
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 Comments
millercommamatt
on 29 Oct 2021
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
on 29 Oct 2021
Stephen23
on 29 Oct 2021
"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
on 30 Oct 2021
"...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
on 30 Oct 2021
Edited: Pelajar UM
on 30 Oct 2021
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
on 30 Oct 2021
Edited: Pelajar UM
on 31 Oct 2021
Stephen23
on 31 Oct 2021
"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{:})
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!