MATLAB: How to read specific part of the text file

readread specific part in file

So, I have text file in Notepad data.txt which contain all information about some image for example
  • image1.gif
  • gif
  • 256
  • 256
  • 155.992455 321.222455 995.452774 741.123478
  • 15 24 35
  • 41 52 64
  • 58 59 50
so I have name of image, extension,height, width, matrix of gray image and matrix of image in this order in file. I made function which receives namefile and parameter which is needed to be read. So I want that the result of function be that parametar from text file for example function:
readformfile('data.txt','MatrixOfImage')
and result should be this
15 24 35
41 52 65
58 59 50
I have written the function but it reads all text from file and I don't know how to read only specific parameter from file
function result=readfromfile(namefile,parameter)
result=fileread(namefile);
end
I would be very grateful if someone could help me.

Best Answer

With Matlab there are many ways. The one below is one of them. Regard the first five lines as a "header" and use textscan.
>> num = cssm()
num =
15 24 35
41 52 64
58 59 50
where
function num = cssm()
fid = fopen( 'cssm.txt' );
cac = textscan(fid,'%f%f%f', 'Headerlines',5, 'CollectOutput',true );
fclose( fid );
num = cac{1};
end
and cssm.txt contains
image1.gif
gif
256
256
155.992455 321.222455 995.452774 741.123478
15 24 35
41 52 64
58 59 50
&nbsp
In response to comment
Try this modified function
>> out = cssm( 'cssm1.txt', 'name_of_image' )
out =
image1.gif
>> out = cssm( 'cssm2.txt', 'color_image' )
out =
78 44 28
77 32 71
55 12 53
>> out = cssm( 'cssm2.txt', 'RBG_image' )
name_of_image, extension, height, width, gray_image, color_image
out =
[]
>> out = cssm( 'cssm1.txt', 'width' )
out =
256
where
function out = cssm( filespec, param )
fid = fopen( filespec );
cac = textscan( fid, '%s', 'Delimiter','\n', 'CollectOutput',true );
fclose( fid );
switch lower( param )
case 'name_of_image'
out = cac{1,1};
case 'extension'
out = cac{2,1};
case 'height'
out = str2double( cac{3,1} );
case 'width'
out = str2double( cac{4,1} );
case 'gray_image'
out = str2num( cac{5,1} );
case 'color_image'
out = str2num( char(cac(6:8,1)) );
otherwise
str = 'name_of_image, extension, height, width, gray_image, color_image';
disp( str )
out = [];
end
end
and cssm2.txt contains
image2.gif
gif
128
128
456.972255 333.2147455 895.441274 125.111278
78 44 28
77 32 71
55 12 53