For loop to extract string with if function

조회 수: 5(최근 30일)
Benedikt Skurk
Benedikt Skurk 2021년 5월 19일
댓글: Stephen23 2021년 5월 20일
Hello,
i have a problem and already working so long on it finding no solution. I have following 2x44 string
Now i want to write a code, that check whether the first line is true or false and, depending on that, the string in line 2 should be processed differently. The 2x44 string is called E. This is my code:
for i = 1:length(E)
if strcmp(E{1,i},'false')
str = extractBetween(Variables,"ElmSite.",".ElmTerm");
elseif strcmp(E{1,i},'true')
str = extractBetween(Variables,"ElmLne","Term");
end
end
As a result i would like to get a 1x44 string which is called for example str and looks like the following
Can someone help me? or give me a hint how it works easier?
  댓글 수: 1
Stephen23
Stephen23 2021년 5월 20일
C = {'ElmSite.1.ElmTerm'; 'ElmSite.2.ElmTerm'; 'ElmLne.3.ElmTerm'; 'ElmLne.4.ElmTerm'};
D = regexp(C,'\d+(?(?<=Lne\.\d+)[^T]+)','match','once')
D = 4×1 cell array
{'1' } {'2' } {'3.Elm'} {'4.Elm'}

댓글을 달려면 로그인하십시오.

채택된 답변

David Fletcher
David Fletcher 2021년 5월 19일
편집: David Fletcher 2021년 5월 19일
Nothing seems to be particularly wrong in the code - the only thing that stands out is that the str variable will be overwritten on each iteration so you only end up with the last value. If you want the output you have stated, you will need to save the str values as the loop progresses. Using a bit of dummy data:
a='false';
b='true';
Data{1,1}=a;
Data{1,2}=a;
Data{1,3}=a;
Data{1,4}=a;
Data{2,1}='ElmSite.1.ElmTerm';
Data{2,2}='ElmSite.2.ElmTerm';
Data{2,3}='ElmSite.3.ElmTerm';
Data{2,4}='ElmSite.4.ElmTerm';
for i = 1:size(Data,2)
if strcmp(Data{1,i},'false')
extract{i} = extractBetween(Data{2,i},"ElmSite.",".ElmTerm");
elseif strcmp(Data{1,i},'true')
extract{i} = extractBetween(Data{2,i},"ElmLne","Term");
end
end
  댓글 수: 1
Benedikt Skurk
Benedikt Skurk 2021년 5월 19일
Thanks a lot! Finally i could figure it out

댓글을 달려면 로그인하십시오.

추가 답변(0개)

범주

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by