Filter löschen
Filter löschen

How to create multiple vectors of different lengths using for end loop?

2 Ansichten (letzte 30 Tage)
Hi,
First, thank you for reading my question. I have a vector called "class" that contains a bunch of ones, twos and threes in random order (i.e. class = 1, 1, 3, 1, 2, 1, 3, 3...). These numbers represent classes, and sometimes there is more than three classes. I need to find the class indices in the vector "class" and store them somehow separately for easy access. Since there is usually a different number of ones, twos and threes in the vector, so far I have been doing it like this:
class_1 = find(class == 1);
class_2 = find(class == 2);
class_3 = find(class == 3);
But often I get more than three classes, which requires me to modify the code. Is there a way to make this work without me having to change the code every time I get different number of classes? for example using the "for end" loop? I know that the code below doesn't work, but it conveys the idea that I'm trying to accomplish:
for i = 1:max(class);
class_(i) = find(class == i);
end;
For example, in the case of three classes, at the end I would have three vectors named according to the indices of the class they contain (class_1, class_2 and class_3)
Or maybe there is a better way of doing this without using the "for end" loop.
Thank you very much for your help,

Akzeptierte Antwort

Nick
Nick am 9 Nov. 2011
I think I see what your trying to do. Basically you just want a quicker way of finding ones, twos and threes and so forth in your vector right?
What you could do is try a structured array instead.
for i=1:max(class)
classindex(i).indices=find(class==i);
classindex(i).number=num2str(i);
end

Weitere Antworten (2)

Walter Roberson
Walter Roberson am 9 Nov. 2011
class_counts = accumarray( class(:), 1 );
The above will work provided that the class values are positive integers; class_counts(k) will contain the total number of entries where the class was equal to k.
If the class numbers are not sequential but are discrete (no 3.2 vs 3.2000001 for example), then
[uclass, uidxa, uidxb] = unique(class);
class_counts = accumarray( uidxb(:), 1 );
And then class_counts(k) would be the count of the number of class entries that were exactly equal to uclass(k)

Srdjan
Srdjan am 9 Nov. 2011
Nick, Walter and Andrei, Thank you for your answers. I tried Nick's method and it works well. The class values are positive integers. I will try the other two suggested solutions also.
Thank you very much for your help

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by