MATLAB - Store specificed data from file in cell array

Submitted by:Andery Smith

Date added:27 June, 2011


This MATLAB code snippet reads in a file stored in the current directory and stores specified lines from the file in a new cell array for manipulation in MATLAB.

Tags: store data

Code Snippet:

infile = '7HVP.pdb'; //Define filename variable
[fid,errMsg] = fopen(infile,'rt'); //Open file for read-only, text
if(fid == -1) //Test that file exists
return; //If does not exist, display error message, terminate.

cellpbd = {0}; //Initialize empty cell array
lines = []; //Initialize empty array
count = 0;
while ~feof(fid); //Use of end of file function, while 'not' end of file
lines = fgetl(fid); //fgetl reads each line in file
if findstr(lines,'ATOM ') == 1 //Test for string inside string (boolean)
count = count +1;
cellpbd{count}=lines; //redefine cell array size == count, filled with lines.

fclose(fid); //Don't forget to close file to free system resource.