String Vector for-loop

조회 수: 8 (최근 30일)
zachary schneider
zachary schneider 2019년 8월 29일
댓글: Jos (10584) 2019년 8월 30일
I recently collected some point data, and the trial number or independent variable is a string, such as:
X = ['a1' 'a2' 'a3' 'b1' 'b2' 'b3'];
I would like to create a for loop using the [1 2 3 1 2 3]. Is there any way to seperate the number and letter, or a way to us a string such as this as a for loop condition.
I do not want to use the index, and am trying to make this work for a much larger set of data, so I am trying to have it work automatically.
  댓글 수: 3
zachary schneider
zachary schneider 2019년 8월 29일
X = ['a1'; 'a2'; 'a3'; 'b1'; 'b2'; 'b3']; is the format, so yes it is a char i believe
Adam
Adam 2019년 8월 29일
So simply
str2num( X(:,2) )
would give what you want.

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

채택된 답변

Stephen23
Stephen23 2019년 8월 29일
편집: Stephen23 2019년 8월 29일
>> str = {'a1','a2','a3','b1','b2','b3'};
>> vec = sscanf([str{:}],'%*[ab]%f',[1,Inf])
vec =
1 2 3 1 2 3
>> vec = str2double(regexp(str,'\d+$','match','once'))
vec =
1 2 3 1 2 3
>> vec = str2double(regexprep(str,'^[a-z]+',''))
vec =
1 2 3 1 2 3
  댓글 수: 3
Stephen23
Stephen23 2019년 8월 29일
편집: Stephen23 2019년 8월 30일
>> cha = ['a1 ';'a2 ';'a3 ';'b1 ';'b2 ';'b3 ']
cha =
a1
a2
a3
b1
b2
b3
>> vec = sscanf(cha(:,2:3).','%f',[1,Inf])
vec =
1 2 3 1 2 3
"How can I make my char array in to a cell array"
out = cellstr(cha)
Jos (10584)
Jos (10584) 2019년 8월 30일
This example strongly suggests that it is always a single digit following a single character that is relevant. If so, this will work too:
cha = ['a1 ';'a2 ';'a3 ';'b1 ';'b2 ';'b3 ']
vec = cha(:,2) - '0'

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by