Perform operation on character arrays
5 ビュー (過去 30 日間)
古いコメントを表示
How can I perform some operations on character cells? For example, after an if statement for a numeric cell array, I get another cell array that has characters instead of numeric values, for instance:
A{1,1}=[a,b,c;a,b,c;a,b,c]
A{1,1} corresponds to a cell array that has numerical values and I want to perform some operations for only the components of the numeric cell array that has "b"s not "a"s and "c"s in the character array.
For example, the original A{1,1} is:
A{1,1}=[1,2,3;4,5,6;7,8,9]
So I want to do some calculations for (2,5 and 8) only. My original cell array in large and I cannot select the positions of all "b"s individually and have to select them in a for loop automatically, so my question is how can I identify the index of these components and performsome some operation on them? Is this even possible?
3 件のコメント
Christopher McCausland
2021 年 7 月 15 日
No problem Marshall,
Sorry I didn't have more time to provide a fuller answer though I see Walter has it covered very well! 'find' and 'ismember' are great for char and table manipulation and can be really powerful in these kind of situations.
Christopher
採用された回答
Walter Roberson
2021 年 7 月 12 日
Example
C = {'a','b','c';'a','b','c';'a','b','c'}
A{1,1} = [1,2,3;4,5,6;7,8,9];
A{1,2} = randi(9, 3, 3);
A{1,3} = randi(9, 3, 3);
celldisp(A)
mask = ismember(C, 'b')
%maybe you want to select only those values into separate arrays
selected_values = cellfun(@(c) c(mask), A, 'uniform', 0)
%maybe you want to sum the corresponding selected values
selected_sum = sum(cell2mat(selected_values),2)
%maybe you want to multiply the selected values by something, leaving the
%rest untouched
times_N = randi(9)
selected_multiplied = cellfun(@(c) c.*~mask + times_N.*c.*mask, A, 'uniform', 0)
celldisp(selected_multiplied)
3 件のコメント
Walter Roberson
2021 年 7 月 15 日
Note: the code for selective multiplication here will fail for infinite values, turning them into nan.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Multidimensional Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!