How do I add a column to a cell array based on existing values in another column?

4 ビュー (過去 30 日間)
nskel
nskel 2019 年 6 月 6 日
コメント済み: nskel 2019 年 6 月 6 日
Hi,
Only a beginner so forgive me for the basic question... but I have a cell array (x) of dimensions 1310x2. Column 1 is a unique identifier; there are two possible values of the second column, either "A" or "B". I want to add a third column which I want to be "1" if Column 2 is "A" and "0" otherwise.
What is the most efficient way to carry this out?
Should I be using an 'if' statement with a loop?
If so, should I be adding a third (blank) column before carrying out the if statement and populating this with 1's or 0's?
Thanks!
  1 件のコメント
nskel
nskel 2019 年 6 月 6 日
Thanks for the answers guys! Really appreciate it... Just out of curiosity let's say instead of 'A' and 'B' Column 2 was made of 2 numerics, say 100 or 200- what is the equivalent to strcmp for numbers in this context or is there a better way to go about it?
Cheers!

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

採用された回答

Alex Mcaulley
Alex Mcaulley 2019 年 6 月 6 日
One option is:
x(:,3) = deal({0});
x(ismember(x(:,2),'A'),3) = deal({1});
  1 件のコメント
Jan
Jan 2019 年 6 月 6 日
Cheaper without deal():
x(:,3) = {0};
x(strcmp(x(:,2),'A'), 3) = {1};

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

その他の回答 (1 件)

Jan
Jan 2019 年 6 月 6 日
編集済み: Jan 2019 年 6 月 6 日
Only a beginner so forgive me for the basic question... but I have a cell array (x) of dimensions 1310x2. Column 1 is a unique identifier; there are two possible values of the second column, either "A" or "B". I want to add a third column which I want to be "1" if Column 2 is "A" and "0" otherwise.
x = {'id1', 'A'; ... % Test data
'id2', 'B'; ...
'id3', 'A'};
Value = {'1', '0'}; % Or do you mean {"1", "0"}, or {1, 0}?
x(:,3) = Value(2 - strcmp(x(:,2), 'A'));
If the logical values 0 and 1 are meant:
x(:, 3) = num2cell(strcmp(x(:, 2), 'A'))

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by