How do i convert a numerical cell array in a vector ?

조회 수: 2 (최근 30일)
Davide Conti
Davide Conti 2019년 10월 29일
댓글: Guillaume 2019년 10월 30일
I have a data table imported from Excel with 304 rows and 75 columns.
At the position {10,30} for example i have a cell with comma delimitation like this:
Arr = {'5,6,16,17,19,21,25,27,28'}
I would like that in the position {10,76} of my matrix there is the same string of numbers converted into row vector.

채택된 답변

Guillaume
Guillaume 2019년 10월 29일
A safer alternative to str2num would be:
sscanf(Arr{1}, '%d,') %assuming all the numbers are integers, otherwise '%f'
  댓글 수: 2
Davide Conti
Davide Conti 2019년 10월 30일
Ok, it works if the arguments of the cells are strings scalars or characters vectors. If I had arguments with only one number? For example as in the second row:
Immagine.png
Guillaume
Guillaume 2019년 10월 30일
You already have a number in the 2nd row (as opposed to textual representation of numbers). There's nothing to do there.
However, note that it's rarely a good idea to mix actual numbers and text in the same container. You will have to test whether each row is actually textual or numeric before using it.
If you wanted to convert that whole column, you could use a loop as follows:
for row = 1:size(yourcellarray, 1)
if ~isnumeric(yourcellarray{row, somecolumnindex})
yourcellarray{row, somecolumnindex} = sscanf(yourcellarray{row, somecolumnindex}, '%d,').';
end
end

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Sebastian Bomberg
Sebastian Bomberg 2019년 10월 29일
Use str2num on the content of the cell:
str2num(Arr{:})
  댓글 수: 1
Guillaume
Guillaume 2019년 10월 29일
편집: Guillaume 2019년 10월 29일
I would be very careful with using str2num on arbitrary input coming from an excel file. str2num is a dangerous function that will happily eval whatever text it is passed so somebody could easily craft an excel file that would make str2num format the hard drive or other nastiness.
e.g. on window see the effect of:
Arr = {'system(''notepad'')'}
str2num(Arr{1}) %opens notepad

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by