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!