필터 지우기
필터 지우기

Efficient code - Get rid of my loop

조회 수: 2 (최근 30일)
jlt199
jlt199 2016년 8월 19일
댓글: Azzi Abdelmalek 2016년 8월 19일
Hi,
I'm reading in some data from a csv file, which for some reason is being read in as strings rather than doubles. Now I need to do some math so need to convert to numbers, but my strings don't all have the same number of characters. Here's an example:
B = {'5085';'10955';'6496';'6497';'2953';'5090'};
The only way I have found to convert this is to use a loop:
for count = 1:size(B,1)
B{count} = str2num(B{count});
end
B = cell2mat(B);
But there must be a more efficient, quicker, method for achieving this conversion. Any suggestions please?

채택된 답변

Star Strider
Star Strider 2016년 8월 19일
The cellfun function works without the loop:
B = {'5085';'10955';'6496';'6497';'2953';'5090'};
Bn = cellfun(@str2num, B)
Bn =
5085
10955
6496
6497
2953
5090
  댓글 수: 3
Star Strider
Star Strider 2016년 8월 19일
My pleasure.
The str2num and other functions don’t work with cell arrays, but cellfun can make most functions compatible with them.
Azzi Abdelmalek
Azzi Abdelmalek 2016년 8월 19일
The cellfun is not more efficient then the for loop

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

추가 답변 (1개)

Azzi Abdelmalek
Azzi Abdelmalek 2016년 8월 19일
  댓글 수: 1
jlt199
jlt199 2016년 8월 19일
Thank you, that works too :D

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

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by