How to implement a set in MATLAB?

94 ビュー (過去 30 日間)
Jonathan Mayers
Jonathan Mayers 2016 年 6 月 23 日
回答済み: Jonathan Mayers 2016 年 6 月 24 日
In the algorithm below, you can see that there is a variable, C, initialized to the empty set. How would I go about creating a set in MATLAB? Because of this confusion I am unclear on how to code lines 5 and 7 of the algorithm. Furthermore, I am unclear of how to implement the condition on line 13. What is the best way to implement this logic?

採用された回答

Jonathan Mayers
Jonathan Mayers 2016 年 6 月 24 日
Thank you for the responses. I have arrived at what I needed and hope it will help anyone in the future viewing this post.
First, each Ci is a different set so C can be a (mx*my+1)-by-N matrix of zeros where each row would a different set Ci.
C = zeros(mx*my+1,N);
Next, the logic of lines 5 and 7 can be coded as below where col_t and col_f are the indices of the column to change when the condition is true or false respectively. They are initialized to 1 before the for loop.
%%line 5
row = (i-1)*mx+j;
C(row,col_t) = n;
col_t = col_t + 1;
%%line 7
row = mx*my+1;
C(row,col_f) = n;
col_f = col_f + 1;
Finally, after line 11 and before the for loop of line 12, you can extract the subset with the following code:
Ci = C(i,:);
And the condition on line 13 would be as Titus answered:
if ismember(n,Ci)

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2016 年 6 月 23 日
If you want an actual set, in the sense of an unordered collection in which there can be at most one "copy" of any given value, then you can use a vector together with the union and setdiff operators.

Titus Edelhofer
Titus Edelhofer 2016 年 6 月 23 日
Hi,
if I see it correctly, your "set" is meant to be a set of numbers? In this case you might simply use a vector in MATLAB. And the empty set in this case would be
C = [];
To test if an element of a "set", use the function ismember, so line 13 would read
if ismember(n, C)
Titus Titus
  1 件のコメント
Jonathan Mayers
Jonathan Mayers 2016 年 6 月 23 日
Thank you. So for example, I can code the assignment in line 5 as below?
index = (i-1)*mx+j;
C(index) = n;

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeTime Series についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by