how to add to matrix in a loop rather than replace

조회 수: 1 (최근 30일)
Jaber Gharib
Jaber Gharib 2018년 3월 13일
답변: BhaTTa 2024년 10월 18일

I like to use the following codes to put members in groups. But as you can see Alkanes are replaced not added up.

species{1}=[0.86 1.27 1.23]; species{2}=[1.4]; species{3}=[4.32 3.49 1.33 1.02 0.83]; species{4}=[8.87 6.89 6.78 6.74 6.72 3.73];

type{1}=['aliohatic' 'aliphatic' 'aliphatic']; type{2}=['cycloalkene']; type{3}=['aliphaticOH' 'alcoholethyl' 'aliphatic' 'aliphatic' 'aliphatic']; %13=aliphaticOH %14=alcoholethyl type{4}=['ArOH' 'aromaticH' 'aromaticH' 'aromaticH' 'aromaticH' 'ArOCH3'] %15=ArOH %16=aromaticH %17=ArOCH3

for iC=1:4 if ismember('ArOH', type{iC}) parent{iC}='Phenols' Phenols=species{iC}

        elseif ismember('aliphaticOH', type{iC})
        parent{iC}='Alcohols'
        Alcohols=species{iC} 
        elseif ismember('cycloalkene', type{iC}) 
            parent{iC}='Alkanes'
        elseif ismember('aliphatic', type{iC}) 
            parent{iC}='Alkanes'
            Alkanes=species{iC}
        else
            parent{iC}='unknown'         
        end
end

답변 (1개)

BhaTTa
BhaTTa 2024년 10월 18일
Hey @Jaber Gharib, in the code you have provided each time when you see a match you are overrding previous value instead of appending it, below i have attached an similiar example where I will be appending the values
species{1} = [0.86 1.27 1.23];
species{2} = [1.4];
species{3} = [4.32 3.49 1.33 1.02 0.83];
species{4} = [8.87 6.89 6.78 6.74 6.72 3.73];
species{5} = [8.87 6.89 6.78 6.74 6.72 3.73];
type{1} = {'aliphatic', 'aliphatic', 'aliphatic'};
type{2} = {'cycloalkene'};
type{3} = {'aliphaticOH', 'alcoholethyl', 'aliphatic', 'aliphatic', 'aliphatic'};
type{4} = {'ArOH', 'aromaticH', 'aromaticH', 'aromaticH', 'aromaticH', 'ArOCH3'};
type{5} = {'ArOH', 'aromaticH', 'aromaticH', 'aromaticH', 'aromaticH', 'ArOCH3'};
% Initialize group variables
Phenols = [];
Alcohols = [];
Alkanes = [];
for iC = 1:5
if ismember('ArOH', type{iC})
parent{iC} = 'Phenols';
Phenols = [Phenols, species{iC}];
elseif ismember('aliphaticOH', type{iC})
parent{iC} = 'Alcohols';
Alcohols = [Alcohols, species{iC}];
elseif ismember('cycloalkene', type{iC})
parent{iC} = 'Alkanes';
Alkanes = [Alkanes, species{iC}];
elseif ismember('aliphatic', type{iC})
parent{iC} = 'Alkanes';
Alkanes = [Alkanes, species{iC}];
else
parent{iC} = 'unknown';
end
end
% Display results
disp('Phenols:');
disp(Phenols);
disp('Alcohols:');
disp(Alcohols);
disp('Alkanes:');
disp(Alkanes);
Hope it helps.

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by