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

1 次查看(过去 30 天)
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

采纳的回答

David Hill
David Hill 2021-11-9
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));

更多回答(1 个)

Sulaymon Eshkabilov
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' ));

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by