Avoid loop for equality

I have a variable
h = 2:2:8
I want to have 4 output variables depending on the 4 differnt h
A = y(s==h(1),:)
As you can see if I have it like this I need to do it 4 times for each h. Is there a possibility to do it like this in one step?
[A1, A2, A3, A4] = y(s==h,:)

6 comentarios

Adam
Adam el 3 de Jul. de 2018
What are y and s?
Stef
Stef el 3 de Jul. de 2018
y is a matrix and s is a column of the matrix
Rik
Rik el 3 de Jul. de 2018
How would you code this in a loop? If you show that in code, it will be easier to find a solution without a loop (or explain why that doesn't exist).
Stef
Stef el 3 de Jul. de 2018
Editada: Stef el 3 de Jul. de 2018
A=zeros(1,4)
for h=1:4
A(h) = y(s==h,:)
end
Rik
Rik el 3 de Jul. de 2018
Try to write a MWE. This way we can recreate your desired result. The code you wrote is probably not what you want (as it overwrites the result every loop iteration), nor is it self-contained. We can't run it, and even if we could, we would not get the result you want.
Rik
Rik el 3 de Jul. de 2018
Despite your edit, this is still not a MWE. We don't have y or s, so we still cannot run this. I would also agree with Guillaume that it is a bad idea to number variables: writing A{1} A{2} A{3} instead of A1 A2 A3 will allow you to easily loop over all elements.

Iniciar sesión para comentar.

Respuestas (1)

Guillaume
Guillaume el 3 de Jul. de 2018

1 voto

Do not number variables. Creating variables A1, A2, ... is a bad idea, it will make for slow, hard to understand and difficult to debug code. If you start numbering variables it means that they're somehow related and would be better stored together in a single container that you can index easily.
It turns out you already have such a container, your y and you're probably better off keeping it as is. If you really need to you can split y into a cell array according to s but it's probably going to make subsequent calculations harder rather than easier:
[~, ~, rowid] = unique(s);
splity = accumarray(rowid, (1:numel(s))', [], {@(rid) y(rid, :)})

Categorías

Más información sobre Performance and Memory en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 3 de Jul. de 2018

Comentada:

Rik
el 3 de Jul. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by