Home > Software engineering >  Efficiency loading a file into Matlab
Efficiency loading a file into Matlab

Time:12-15

I am trying to load a file in Matlab. But I am a bit confused about the best way to do it.

The file has 3 columns and looks like the screenshot below: enter image description here

This file I can load very quickly by doing load('c').

However, I had to add 2 NaNs on the bottom row.

The original file actually looks like the file below:

enter image description here

Now if I do load('c') on the file below I get the error:

Error using load
Unable to read file 'c'. Input must be a MAT-file or an ASCII file containing numeric
data with same number of columns in each row.

Of course I can use ImportData to import this file, but it is just soooo slow to import it.

Any suggestions?

CodePudding user response:

You should be able to use c = readtable('c'). This should automatically change the empty entries to "NaN" by default, but if not, there is a way to set that in the options.

If I have a file that is tricky to import (prior to readtable()...that made things a lot easier in the last few years), I will often use the Import Data tool (if its a really big file you can make a mock-up of the complicated file so it loads faster) then change all the import settings as I would want it, then where the green check says "Import Selection" use the black drop down arrow to select "Generate Function." This will give you the coded way of setting everything up to get the file in just the way you want it.

load() is better suited for reading in previously saved '.mat' files that were created in Matlab.

CodePudding user response:

Here's a low-level approach, which might be faster than other methods:

filename = 'c'; % name of the file
N = 3; % number of columns
fid = fopen(filename, 'r'); % open file for reading
x = fscanf(fid, '%f'); % read all values as a column vector
fclose(fid); % close file
x = [x; NaN(N-mod(numel(x)-1,N)-1, 1)]; % include NaN's to make length a multiple of N
x = reshape(x, N, []).'; % reshape to N columns in row-major order
  • Related