Subhankar Ghosh
Subhankar Ghosh

Reputation: 469

Array of sets in Matlab

Is there a way to create an array of sets in Matlab.

Eg: I have:

a = ones(10,1);
b = zeros(10,1);

I need c such that c = [(1,0); (1,0); ...], i.e. each set in c has first element from a and 2nd element from b with the corresponding index.

Also is there some way I can check if an unknown set (x,y) is in c.

Can you all please help me out? I am a Matlab noob. Thanks!

Upvotes: 0

Views: 230

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 102439

If you would like to get logical value regarding if p is in C, maybe you can try the code below

any(sum((C-p).^2,2)==0)

or

any(all(C-p==0,2))

Example

C = [1,2;
     3,-1;
     1,1;
     -2,5];

p1 = [1,2];
p2 = [1,-2];

>> any(sum((C-p1).^2,2)==0) # indicating p1 is in C
ans = 1
>> any(sum((C-p2).^2,2)==0) # indicating p2 is not in C
ans = 0
>> any(all(C-p1==0,2))
ans = 1
>> any(all(C-p2==0,2))
ans = 0

Upvotes: 0

Max
Max

Reputation: 4045

There are not sets in your understanding in MATLAB (I assume that you are thinking of tuples on Python...) But there are cells in MATLAB. That is a data type that can store pretty much anything (you may think of pointers if you are familiar with the concept). It is indicated by using { }. Knowing this, you could come up with a cell of arrays and check them using cellfun

% create a cell of numeric arrays
C = {[1,0],[0,2],[99,-1]}
% check which input is equal to the array [1,0]
lg = cellfun(@(x)isequal(x,[1,0]),C)

Note that you access the address of a cell with () and the content of a cell with {}. [] always indicate arrays of something. We come to this in a moment.

OK, this was the part that you asked for; now there is a bonus:

That you use the term set makes me feel that they always have the same size. So why not create an array of arrays (or better an array of vectors, which is a matrix) and check this matrix column-wise?

% array of vectors (there is a way with less brackets but this way is clearer):
M = [[1;0],[0;2],[99;-1]]
% check at which column (direction ",1") all rows are equal to the proposed vector:
lg = all(M == [0;2],1)

This way is a bit clearer, better in terms of memory and faster. Note that both variables lg are arrays of logicals. You can use them directly to index the original variable, i.e. M(:,lg) and C{lg} returns the set that you are looking for.

Upvotes: 3

Related Questions