How to retrieve the index of positions starting with a specific character in a cell array?

1 view (last 30 days)
I have two arrays. array1 contains values and array2 contains characters.
Each character of array2 is associated with the value in array1 i.e. array1(n) goes with array2(n).
I want to compute the sum of the values in array1 corresponding to all the entries in array2 starting with the same letter (i.e. A, B or C).
I do not know how to retrieve the index of all the positions starting with the character 'A', 'B' or 'C' in a cell array.
%Basic example with n=5
x1 = 5000;
x2 = 3000;
x3 = 1000;
x4 = 800;
x5 = 500;
array1 = [x1,x2,x3,x4,x5];
array2 = {'A1','A2','B1','C1','A3'}
%I want to compute the following
totA = array1(1)+array1(2)+array1(5)
totB = array1(2)
totC = array1(3)
Thank you

Accepted Answer

David Hill
David Hill on 9 Nov 2021
Simple loop does the trick.
idxA=[];idxB=[];idxC=[];
for m=1:length(array2)
switch array2{m}(1)
case 'A'
idxA=[idxA,m];
case 'B'
idxB=[idxB,m];
case 'C'
idxC=[idxC,m];
end
end
totA = sum(array1(idxA));
totB = sum(array1(idxB));
totC = sum(array1(idxC));

More Answers (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov on 9 Nov 2021
x1 = 5000;
x2 = 3000;
x3 = 1000;
x4 = 800;
x5 = 500;
array1 = ([x1,x2,x3,x4,x5]).';
array2 = categorical({'A1';'A2';'B1';'C1';'A3'});
T =array2table(array1);
T.array2=array2;
totA = sum(T.array1(T.array2=='A1' | T.array2=='A2' | T.array2=='A3' ));
totB = sum(T.array1(T.array2=='B1' | T.array2=='B2' | T.array2=='B3' ));
totC = sum(T.array1(T.array2=='C1' | T.array2=='C2' | T.array2=='C3' ));

Products


Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by