How can I make a set of numbers and add numbers to it later?
47 views (last 30 days)
Show older comments
I want to create a set of numbers, like for example all odd numbers divisible by 3: S = {3, 9, 15} etc. I have thought of creating a vector, but in the calculation matlab doesn't see a vector as a set of numbers. Later on in my calculation I want to add even more numbers to the set S, for example I want to add the numbers {21, 27}. I have no clue how to fix this in matlab, the only thing I thought of was, as I said, creating a vector but that option doesn't seem to work for me. After creating a set of numbers I want to pick the elements out of the set and check whether they are divisible by 6 for example. But as soon as I know how to make such a set, my expectation is that picking some element out of it would be a matter of trial and error.
Is there an option in matlab to create a set of self chosen numbers, and add later even more numbers to the same set and make some more calculations with the expanded set after all? Thanks in advance.
2 Comments
Azzi Abdelmalek
on 25 Dec 2013
I think you can make your question more clear and breve. For example, what do you mean by: matlab doesn't see a vector as a set of numbers. Give a short example and show what are you expecting as result.
Accepted Answer
Matt J
on 25 Dec 2013
Edited: Matt J
on 25 Dec 2013
Is there an option in matlab to create a set of self chosen numbers, and add later even more numbers
Yes, you just use a vector to represent your set and then concatenate more numbers to it, e.g.,
>> numset=[1 5 8 3], expanded=[numset, [4 100,7]]
numset =
1 5 8 3
expanded =
1 5 8 3 4 100 7
2 Comments
Matt J
on 25 Dec 2013
Edited: Matt J
on 25 Dec 2013
I still don't know how to pick a number out of the set of numbers and check whether it is equal to 8 for example
>> numset=[1 5 8 3];
>> numset(1)==8,
ans =
0
>> numset([2,3,4])==8
ans =
0 1 0
>> any(numset==8)
ans =
1
Also, I want to add numbers to it with the help of a loop
That's usually a bad idea. It involves a lot of repeated memory allocation, but you can do it by iterative concatenation,
>> numset=[1,2,3]; for n=4:6, numset=[numset,n], end
numset =
1 2 3 4
numset =
1 2 3 4 5
numset =
1 2 3 4 5 6
More Answers (1)
See Also
Categories
Find more on Loops and Conditional Statements 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!