Effacer les filtres
Effacer les filtres

Strings and numbers in the same matrix

384 vues (au cours des 30 derniers jours)
Erik
Erik le 26 Juil 2011
Commenté : Jan le 18 Juil 2021
Ok, so I have a bunch of data. I want to store this data in some kind of matrix with rows and columns for easy usage. The data is made up of both strings and regular numbers, mixed. Storing the data as a matrix is fine (I've used a string matrix), but getting to the data afterwards prooves to be troublesome.
Getting the strings out are no problem, but I need to be able to calculate other stuff with the numbers. Since I've saved everything as a string matrix I can't just use the numbers as they are, so I tried using str2double, but that just returns NaN.
I've also tried using a regular matrix to store the data, but that just stores the strings in individual letters, which won't work at all, since the length of the strings themselves will vary between data sets.
Any ideas on how to solve this problem? It doesn't really matter if it's a string matrix or a regular one, as long as it works!
Thanks in advance, Erik

Réponse acceptée

Jan
Jan le 26 Juil 2011
If you want to store numbers and strings in the same object, use a CELL:
C = cell(2, 2);
C{1, 1} = 1;
C{1, 2} = rand(10);
C{2, 1} = 'Hello';
C{2, 2} = {'This', 'is', 'a', 'sentence', 'as', 'cellstring'};
  3 commentaires
Muhammad Ridwanur Rahim
Muhammad Ridwanur Rahim le 17 Juil 2021
Hi @Jan,
if my matrix size is , let's say, 30-by-5, then in this case, creating a cell becomes quite tideous. is there any other alternative?
thanks.
Jan
Jan le 18 Juil 2021
If you have to write down 150 chunks of data, there is no way to avoid this. You could write the data to a file and import it into a cell, but you still have to type the data.
What does your cell contain? If the data can be created by code, this is easy, e.g.:
C = sprintfc('%d', ones(30, 5)) % Not documented

Connectez-vous pour commenter.

Plus de réponses (1)

Jessica
Jessica le 26 Juil 2011
I've used str2double() a lot and never had it return NaN.
Are you trying to convert something like A = 'abc123' to a number? That's the only way I can think of that you're getting NaN with str2double(). If that's the case, you'll have to separate out the numbers from the characters first.
You can use regexp for this (help regexp).
% The following will give you the indices of the numbers in your string:
digit_index = regexp(A,'\d') ;
numbers = str2double(A(digit_index)) ;
I hope this helps.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by