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

35 ビュー (過去 30 日間)
nskel
nskel 2019 年 6 月 12 日
コメント済み: nskel 2019 年 6 月 12 日
I have a cell array (x) of dimensions 900x2. Column 1 is a unique identifier; there are two possible values of the second column, either "1" or "2". I want to add a third column which I want to be "1" if Column 2 is "1" and "0" otherwise.
I had previously asked a similar question where there were strings instead of numbers in Column 2 and a strcmp function was used but I would like to know similar function regarding numbers.
Any help appreciated!
  3 件のコメント
Jan
Jan 2019 年 6 月 12 日
"1" is a string, '1' is a char or char vector, 1 is a number, either as single, double or an integer type. Instead of explaining the contents of the cell as text, prefer to use Matlab syntax, because then it is clear immediately:
x = {'asd', 1; ...
'bsd', 0};
% And you want to get:
y = {'asd', 1, 0; ...
'bsd', 0, 1};
Is this correct?
nskel
nskel 2019 年 6 月 12 日
Yes, thanks! The second column contains integers.
Apologies!
... and yes that is the output I am looking for!

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

回答 (3 件)

Jan
Jan 2019 年 6 月 12 日
編集済み: Jan 2019 年 6 月 12 日
x = {'asd', 1; ...
'bsd', 0};
x(:, 3) = num2cell(1 - cell2mat(x(:, 2)))
% or:
Value = {0, 1};
x(:, 3) = Value(2 - cell2mat(x(:, 2)))
This was one of the approaches for the char data:
Value = {'1', '0'};
x(:,3) = Value(2 - strcmp(x(:, 2), 'A'));
Here you can use the values to create the index instead of strcmp, but the equivalence is clear.

Stephen23
Stephen23 2019 年 6 月 12 日
>> x = {'x1',1';'x2',2;'x3',1}
x =
'x1' [1]
'x2' [2]
'x3' [1]
>> x(:,3) = {0};
>> x([x{:,2}]==1,3) = {1}
x =
'x1' [1] [1]
'x2' [2] [0]
'x3' [1] [1]

Joel Handy
Joel Handy 2019 年 6 月 12 日
編集済み: Joel Handy 2019 年 6 月 12 日
Obviously replace myCellArray with whatever your array is called.
isTwo = cellfun(@(x) x == 2, myCellArray(:,2));
myCellArray(:,3) = num2cell(double(isTwo))
Alternatively
isTwo = [myCellArray{:,2}]' == 2;
myCellArray(:,3) = num2cell(double(isTwo));
I'm not sure which is faster off hand.

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by