我在这里遇到了我的Matlab问题。我有一个* .txt文件,看起来像这样:
1
2
2
X50
2
2
2
X79
这意味着在坐标(1,2,2)处f(x) - 值为50,在坐标(2,2,2)处f(x) - 值为79.我试图读取这到Matlab所以我有一个矢量(或者使用repmat一个类似网格的矩阵)用于x和一个用于y。我不需要z,因为它不会改变过程。 另外我想读f(x)-value所以我可以使用surf()绘制整个事物。
如果我使用
[A] = textread('test.txt','%s')
它总是给我整件事......有人可以给我一个想法吗?我正在考虑把这个东西放在一个循环中,类似于这个伪代码
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
任何提示?感谢
答案 0 :(得分:1)
假设文本文件中的数据设置类似于线1,2,3是XYZ坐标点,下一行(第四行)是函数值。然后5,6,7是下一组XYZ坐标点,后面跟着该组的第8行的函数值,依此类推,看看这是否适合你 -
%// 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
更有力的方法 -
%// 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