How can I combine charactor array with a numerical arrays?
4 次查看(过去 30 天)
显示 更早的评论
I have more than 1000 data sets like the attached file, just need to extract all the details except GG and NN. I jus use the following programme to import from text file and extract the details. but I can not combine the character array and numeric array after running the programme.
filename = 'L:\R1.txt';
delimiter = {',','-'};
formatSpec = '%s%s%s%s%s%*s%*s%s%[^\n\r]';
fileID = fopen(filename,'r');
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'ReturnOnError', false);
fclose(fileID);
raw = repmat({''},length(dataArray{1}),length(dataArray)-1);
for col=1:length(dataArray)-1
raw(1:length(dataArray{col}),col) = dataArray{col};
end
numericData = NaN(size(dataArray{1},1),size(dataArray,2));
for col=[2,3,4,5]
rawData = dataArray{col};
for row=1:size(rawData, 1);
regexstr = '(?<prefix>.*?)(?<numbers>([-]*(\d+[\,]*)+[\.]{0,1}\d*[eEdD]{0,1}[-+]*\d*[i]{0,1})|([-]*(\d+[\,]*)*[\.]{1,1}\d+[eEdD]{0,1}[-+]*\d*[i]{0,1}))(?<suffix>.*)';
try
result = regexp(rawData{row}, regexstr, 'names');
numbers = result.numbers;
invalidThousandsSeparator = false;
if any(numbers==',');
thousandsRegExp = '^\d+?(\,\d{3})*\.{0,1}\d*$';
if isempty(regexp(thousandsRegExp, ',', 'once'));
numbers = NaN;
invalidThousandsSeparator = true;
end
end
if ~invalidThousandsSeparator;
numbers = textscan(strrep(numbers, ',', ''), '%f');
numericData(row, col) = numbers{1};
raw{row, col} = numbers{1};
end
catch me
end
end
end
rawNumericColumns = raw(:, [2,3,4,5]);
rawCellColumns = raw(:, 1);
v = rawCellColumns(:, 1);
D1 = cell2mat(rawNumericColumns(:, 1));
D2 = cell2mat(rawNumericColumns(:, 2));
D3 = cell2mat(rawNumericColumns(:, 3));
t = cell2mat(rawNumericColumns(:, 5));
but then I can not use the disp([v D1 D2 D3 t]). if I use it there is an error. please kindly help me to solve this problem
2 个评论
Stephen23
2016-3-14
编辑:Stephen23
2016-3-14
" I can not combine the character array and numeric array"
This is correct: numeric arrays are numeric arrays, and character arrays are character arrays. They are different things. They don't just "combine" into something that you can display (see ##).
## Of course it is easy to convert a character array to its equivalent character values, which are numeric, but these are not usually what people wish to display...
回答(1 个)
Eric Lowry
2016-3-16
You are seeing an error when you run your disp command because you are concatenating v, which is a cell array, with D1, D2, D3, and t, which are matrices. You could use something like this, instead:
disp([v num2cell(D1) num2cell(D2) num2cell(D3) num2cell(t)]);
This will convert the matrices into cell arrays and concatenate the results.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!