MATLAB: How can extract specific numbers from a string?? extract specific numbers from a stringmatrixnumstring I have the string c={ 4 of 5 stars, 5 of 5 stars, 5 of 5 stars, 3 of 5 stars, 3 of 5 stars, 4 of 5 stars}. How can extract to a matrix the bold numbers ???? thank you!!! Best Answer You could use a regular expression. Assuming all the numbers you want to extract are integer:str = 'c={ 4 of 5 stars, 5 of 5 stars, 5 of 5 stars, 3 of 5 stars, 3 of 5 stars, 4 of 5 stars}';starcount = str2double(regexp(str, '\d+(?= of)', 'match'))The regular expression matches any sequence of digit immediately followed by ' of'. Related SolutionsMATLAB: Exclude Digits from String using Regexp in MATLAB regexp(str,'[^\d_\.]*','match')orregexp(str,'[a-zA-Z]*','match') MATLAB: Create a Matrix from a cell array Your post is not very clear, not help with the fact that your example does not use valid matlab syntax. Possibly, that's what you want:ratings = {'Value,Rooms,Cleanliness,Service', '2 of 5 stars,2 of 5 stars,4 of 5 stars,2 of 5 stars'; ... 'Value,Location,Sleep Quality,Rooms,Cleanliness,Service', '5 of 5 stars,5 of 5 stars,5 of 5 stars,5 of 5 stars,5 of 5 stars,5 of 5 stars'; ... 'Location,Rooms,Cleanliness,Service', '4 of 5 stars,1 of 5 stars,3 of 5 stars,4 of 5 stars'}%The above is not a very useful way to store data, so split it:ratinglabels = cellfun(@(r) strsplit(r, ','), ratings(:, 1), 'UniformOutput', false);ratingscores = cellfun(@(r) str2double(regexp(r, '\d+(?= of)', 'match')), ratings(:, 2), 'UniformOutput', false); %extract score%get unique labels, and mapping between original array and label column:[labels, ~, destinationcolumn] = unique([ratinglabels{:}]); %get row destination for each score:destinationrow = repelem(1:size(ratings, 1), cellfun(@numel, ratingscores))';%create output matrix and fill with score. Default value if score is missing is NaN:scores = nan(size(ratings, 1), numel(labels));scores(sub2ind(size(scores), destinationrow, destinationcolumn)) = [ratingscores{:}];%pretty display:scores = array2table(scores, 'VariableNames', matlab.lang.makeValidName(labels))%export to excel:writetable(scores, 'someexcelfile.xlsx'); Related QuestionRegular Expressions using regexpConvert a single char array to a vector of doubles with a non-whitespace delimiter [R2017b, Windows7]Convert String to Numerical MatrixHow to use regexp for the followingHow to extract only floating numbers from a stringExtract integers from random strings
Best Answer