Indexing letters and numbers in strings

Hello everybody. I have this matrix set up by strings. The first row is "employee number" and the first column is "project" number.
If i want to know for project 1 which number is behind the letter "L" (22). How do i do that?
Skema3 =
'0' '1' '2' '3' '4' '5' '6'
'1' 'L22' 'P8' '1' 'P0' '0' '0'
'2' '0' 'P48' 'L63' '0' '0' 'P0'
'3' 'P93' '0' 'P75' 'L18' 'P30' '0'
'4' '0' 'L3' '1' '0' 'P5' '0'
I have made the above matrix from an excel spreadsheet using this code:
[~, ~, raw] = xlsread('ProjektskemaU.xlsx');
expression = '\/';
numtext = regexp(raw, expression, 'split')
Skema3 = cellfun(@cell2mat, numtext,'UniformOutput',false)
str2double(Skema3(i,1))
In excel the letters and numbers were separated by "/".
Thank you very much

Answers (1)

Skema3 ={
'0' '1' '2' '3' '4' '5' '6'
'1' 'L22' 'P8' '1' 'P0' '0' '0'
'2' '0' 'P48' 'L63' '0' '0' 'P0'
'3' 'P93' '0' 'P75' 'L18' 'P30' '0'
'4' '0' 'L3' '1' '0' 'P5' '0' }
% Save a few strcmps by making first row/col numeric
Skema3(:,1) = cellfun(@str2double,Skema3(:,1),'UniformOutput',false);
Skema3(1,:) = cellfun(@str2double,Skema3(1,:),'UniformOutput',false);
% Get number
N = regexp(Skema3(2:end,cellfun(@(x)x==1,Skema3(1,:))),'L(\d*)','tokens');
% Unpack
N = [N{:}];
N = cellfun(@str2double,[N{:}])
A few hints:
  • You might want to use a table for this, that will make it easier to index (i.e. no cellfuns!)
  • You could bring this in with the import tool and generate code rather than dealing with xlsread yourself. This will allow you to bring it in as a cell or a table.

2 Comments

Thank you very much. This actually works. Can you help me if i want to choose which row i want to extract the number from?
For example. You found the value from when column 1 equalled "1". What if i want to find for "2".
Change x==2
This is why I would use a table, you can then index by location or name. Take a few minutes and read through the doc for them here:

Sign in to comment.

Categories

Asked:

on 9 Jun 2015

Commented:

on 9 Jun 2015

Community Treasure Hunt

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

Start Hunting!