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 件のコメント

Adam
Adam 2019 年 8 月 29 日
Do you really mean a string or a char? What you show just evaluates as
'a1a2a3b1b2b3'
with all the individual quotation marks irrelevant. Is that what you actually have?
X = ["a1" "a2" "a3" "b1" "b2" "b3"];
would be a string array, or
X = ['a1'; 'a2'; 'a3'; 'b1'; 'b2'; 'b3'];
would give you a char array from which extracting the numbers is simply a case of taking the 2nd column, if all letters and numbers will be, as in your example, no longer than a single character long each.
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 日

0 投票

>> 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 件のコメント

zachary schneider
zachary schneider 2019 年 8 月 29 日
sorry if my formatting was off, the str data looks like this:
str =
120×3 char array
'a1 '
'a2 '
'a3 '
'b1 '
'b2 '
'b3 '
i am getting an error with the sscanf command. How can I make my char array in to a cell array
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 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by