Perform operation on character arrays
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
MarshallSc
el 12 de Jul. de 2021
Comentada: MarshallSc
el 16 de Jul. de 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 comentarios
Christopher McCausland
el 15 de Jul. de 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
Respuesta aceptada
Walter Roberson
el 12 de Jul. de 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 comentarios
Walter Roberson
el 15 de Jul. de 2021
Note: the code for selective multiplication here will fail for infinite values, turning them into nan.
Más respuestas (0)
Ver también
Categorías
Más información sobre Multidimensional Arrays en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!