Kathiieee
Kathiieee

Reputation: 211

read textfile in Matlab

I am quite stuck with my Matlab problem here.. I have a *.txt file that looks like this:

1

2

2

x50

2

2

2

x79

which means that at the coordinates (1,2,2) the f(x)-value is 50 and at coordinates (2,2,2) the f(x)-value is 79. I am trying to read this into Matlab so I have for a vector (or using repmat a meshgrid-like matrix) for x and one for y. I will not need z since it will not change over the process. Also I want to read in the f(x)-value so I can plot the whole thing using surf().

If i use

   [A] = textread('test.txt','%s') 

it always gives me the whole thing... Can someone give me an idea please? I am thinking about putting the thing in a loop, something like this pseudocode

   for i=1 to 50
   xpos = read first line
   ypos  =read next line
   zpos = read next line (or ignore.. however..)
   functionvalue= read next line
   end

Any hints? Thanks

Upvotes: 1

Views: 91

Answers (1)

Divakar
Divakar

Reputation: 221504

Assuming that the data setup in the text file is like lines 1,2,3 are XYZ coordinate points and the next line (fourth line) is the function value. Then 5,6,7 are the next set of XYZ coordinate points followed by the function value on the 8th line for that set and so on with such a repeating format, see if this works for you -

%// Read data from text file
text_data = textread(inputfile,'%s') 
data = reshape(text_data,4,[])

%// Get numeric data from it
data(end,:) = strrep(data(end,:),'x','')
%// OR  data(end,:) = arrayfun(@(n) data{end,n}(2:end),1:size(data,2),'Uni',0)
data_numeric = str2double(data)

%// Separate XYZ and function values
xyz = data_numeric(1:3,:)' %//'# Each row will hold a set of XYZ coordinates
f_value = data_numeric(end,:) %// function values

A bit more robust approach -

%// Read data from text file
txtdata = textread(inputfile,'%s');

%// ----------- Part I: Get XYZ ---------------------
%// Find cell positions where the first character is digit indicating that
%// these are the cells containing the coordinate points
digits_pos_ele = isstrprop(txtdata,'digit');
digits_pos_cell = arrayfun(@(x) digits_pos_ele{x}(1),1:numel(digits_pos_ele));

%// Convert to numeric format and reshape to have each row holding each set
%// of XYZ coordinates
xyz_vals = reshape(str2double(txtdata(digits_pos_cell)),3,[])'; %//'

%// ----------- Part II: Get function values ---------------------
%// Find the positions where cell start with `x` indicating these are the
%// function value cells
x_start_pos = arrayfun(@(n) strcmp(txtdata{n}(1),'x'),1:numel(txtdata));

%// Collect all function value cells and find the function value
%// themeselves by excluding the first character from all those cells
f_cell = txtdata(x_start_pos);
f_vals = str2double(arrayfun(@(n) f_cell{n}(2:end), 1:numel(f_cell),'Uni',0))'; %//'

%// Error checking
if size(xyz_vals,1)~=size(f_vals,1)
    error('Woops, something is not right!')
end

Upvotes: 1

Related Questions