converting cell string into number
显示 更早的评论
hello every one; how to convert string in cell into number where each character positioned in one column except the element position 18 or value 24.
example:
wm={'000' '402' '101' '000' '000' '0124' '011'};
estimated result:
y=[0;0;0;0;0;2;1;0;1;0;0;0;0;0;0;0;1;24;o;1;1];
回答(2 个)
Geoff Hayes
2015-5-16
abdullahi - you can try the following code which iterates over each element in the cell array and splits each string into single digits. When the 18th is encountered, then the remaining portion of that string is used (this would be the 24).
y = [];
pos = 1;
% iterate over each string in the cell array
for k=1:length(wm)
% grab the string
str = wm{k};
% iterate over each character in the string
for v=1:length(str)
% if not at the 18th position then extract the single digit
if pos ~= 18
y = [y ; str2double(str(v))];
pos = pos + 1;
% else at the 18th position so extract the remaining digits of string
else
y = [y ; str2double(str(v:end))];
pos = pos + 1;
break;
end
end
end
Try the above and see what happens!
Andrei Bobrov
2015-5-16
wm={'000' '402' '101' '000' '000' '0124' '011'};
z = cellfun(@(x){x(1),x(2),x(3:end)},wm,'un',0);
y = str2double([z{:}]);
类别
在 帮助中心 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!