MATLAB: Extract coloumns from .mat file

r2017a

I have a .mat file which consist of a 22253519×5 double. I need to extract first three coloums only and save them in another .mat file having 2253519×3 double data. All the rows are to be considered.
I have no clue about this. New to MATLAB. Any help would be appreciated.

Best Answer

The below would be easier if you only had one variable stored in the .mat file and you knew the name of the variable. The below code does not assume that there is only one variable and does not assume that the variables have any particular names; the code takes the first three columns of all of the variables that are present, and creates the new .mat file using all of the same variable names.
filename = 'YourFile.mat';
newfile = 'YourNewFile.mat';
datastruct = load(filename);
newstruct = structfun(@(M) M(:,1:3), datastruct, 'uniform', 0);
save(newfile, 'newstruct', '-struct');
Related Question