Basic question about loops
Mostrar comentarios más antiguos
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 comentarios
millercommamatt
el 29 de Oct. de 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
el 29 de Oct. de 2021
Stephen23
el 29 de Oct. de 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
el 30 de Oct. de 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
el 30 de Oct. de 2021
Editada: Pelajar UM
el 30 de Oct. de 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
el 30 de Oct. de 2021
Editada: Pelajar UM
el 31 de Oct. de 2021
Stephen23
el 31 de Oct. de 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{:})
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Matrix Indexing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!