1

I have an cell-array of dimensions 1x6 like this:

A = {'25_2.mat','25_3.mat','25_4.mat','25_5.mat','25_6.mat','25_7.mat'};

I want to read for example from the A{1} , the number after the '_' i.e 2 for my example

3 Answers 3

1

Using cellfun, strfind and str2double

out = cellfun(@(x) str2double(x(strfind(x,'_')+1:strfind(x,'.')-1)),A)

How does it work?

This code simply finds the index of character one number after the occurrence of '_'. Lets call it as start_index. Then finds the character one number lesser than the index of occurrence of '.' character. Lets call it as end_index. Then retrieves all the characters between start_index and end_index. Finally converts those characters to numbers using str2double.

Sample Input:

A = {'2545_23.mat','2_3.mat','250_4.mat','25_51.mat','25_6.mat','25_7.mat'};

Output:

>> out

out =

23     3     4    51     6     7
Sign up to request clarification or add additional context in comments.

4 Comments

that's fine for 1 to 9 once I have for exemple 25_10.mat | 25_11.mat ... it returns: 1 1 but I want: 10 11 so finally I want to have with the same function : 2 3 4 5 6 7 8 9 10 11 etc..
@Devel Edited for that. Can you check it out?
just one more question please, if i want just only one number example A(1) I mean i want only the "2" how to deal?
@Devel out(1) should do.. Add it after the code. (you can do it for any cell number)
0

You can access the contents of the cell by using the curly braces{...}. Once you have access to the contents, you can use indexes to access the elements of the string as you would do with a normal array. For example:

test = {'25_2.mat', '25_3.mat', '25_4.mat', '25_5.mat', '25_6.mat', '25_7.mat'}
character = test{1}(4);

If your string length is variable, you can use strfind to find the index of the character you want.

Comments

0

Assuming the numbers are non-negative integers after the _ sign: use a regular expression with lookbehind, and then convert from string to number:

numbers = cellfun(@(x) str2num(x{1}), regexp(A, '(?<=\_)\d+', 'match'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.