Error using cat. Dimensions of arrays being concatenated are not consistent.

1 view (last 30 days)
Hi everybody,
i'm trying to import an ascii file in matlab and change comma with point. I'm using this code found in the community. It give me an error "Error using cat. Dimensions of arrays being concatenated are not consistent.". I should have a 7013x10139 double.
I don't know how to fix it. Any help? The file is attached here.
fid = fopen('zero_mac_cluster1.asc', 'rb');
strings = textscan(fid, '%s', 'Delimiter', '');
fclose(fid);
decimal_strings = regexprep(strings{1}, ',', '.');
data = cellfun(@str2num, decimal_strings, 'uni', 0);
zero = cat(1, data{:});
zero(zero == -9999) = NaN;

Accepted Answer

Stephen23
Stephen23 on 22 Mar 2019
Edited: Stephen23 on 22 Mar 2019
That is not very well designed code: the regexp is overkill, and the str2num with cellfun is likely not very efficient (as well as hiding evil eval inside...).
The code below imports the header into a structure hdr and the numeric data into matrix out (with class single to save memory):
str = fileread('zero_mac_cluster1.asc');
str = strrep(str,',','.');
% Parse Header:
opt = {'MultipleDelimsAsOne',true};
hdr = textscan(str,'%s%f',6,opt{:});
hdr = cell2struct(num2cell(hdr{2}),hdr{1});
% Parse Matrix:
opt = {'HeaderLines',numel(fieldnames(hdr)), 'CollectOutput',true};
fmt = repmat('%f32',1,hdr.ncols);
out = textscan(str,fmt,opt{:});
out = out{1};
out(out==hdr.NODATA_value) = NaN;
And checking:
>> hdr
hdr =
ncols: 10139
nrows: 7013
xllcorner: 1557267.2310345
yllcorner: 4850030.77
cellsize: 10
NODATA_value: -9999
>> size(out) % matches the file rows, which is NOT what the header states!
ans =
6065 10139
>> out(~isnan(out))
ans =
10
1.25
21.75
24.25
22.25
1.25
6.25
24.25
0
38.25
7.5
1.75
1
1.25
0.25
2.25
7
0.25
36.75
0.5
0
20.5
2.75
22.25
4.5
1.5
3.25
1.75
0.25
0
1.25
2.5
30.25
27.25
2.75
0
1
0.3846154
0.75
1
3.75
12.77778
28.75
12
0
3.181818
1.5
0
5.5
12
66.92308
0
0
1.75
0.25
0
5
45.75
9.75
0
20.5
24.25
0
19.75
2.25
0
1
23.5
0
0
0.25
1
0
12
21.38889
1.75
0.2777778
34.5
8
0.5
0.25
16.75
4
0
-99
2.25
2.5
45.25
0.25
0
5.5
2.25
3.75
3.75
6.75
0
1.75
Note that the memory requirements are not insignificant:
>> whos out
Name Size Bytes Class Attributes
out 6065x10139 245972140 single

More Answers (0)

Categories

Find more on Large Files and Big Data in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!