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
댓글 수: 0
채택된 답변
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
2021년 11월 9일
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' ));
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!