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!