Perform operation on character arrays
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
MarshallSc
am 12 Jul. 2021
Kommentiert: MarshallSc
am 16 Jul. 2021
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 Kommentare
Christopher McCausland
am 15 Jul. 2021
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
Akzeptierte Antwort
Walter Roberson
am 12 Jul. 2021
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 Kommentare
Walter Roberson
am 15 Jul. 2021
Note: the code for selective multiplication here will fail for infinite values, turning them into nan.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!