当前位置: 动力学知识库 > 问答 > 编程问答 >

matlab - Importing text file into matrix form with indexes as strings?

问题描述:

I'm new to Matlab so bear with me. I have a text file in this form :

b0002 b0003 999

b0002 b0004 999

b0002 b0261 800

I need to read this file and convert it into a matrix. The first and second column in the text file are analogous to row and column of a matrix(the indices). I have another text file with a list of all values of 'indices'. So it should be possible to create an empty matrix beforehand.

b0002

b0003

b0004

b0005

b0006

b0007

b0008

Is there anyway to access matrix elements using custom string indices(I doubt it but just wondering)? If not, I'm guessing the only way to do this is to assign the first row and first column the index string values and then assign the third column values based on the first text file. Can anyone help me with that?

网友答案:

You can easily convert those strings to numbers and then use those as indices. For a given string, b0002:

s = 'b0002'
str2num(s(2:end); % output = 2

Furthermore, you can also do this with a char matrix:

t = ['b0002';'b0003';'b0004']
t =

b0002
b0003
b0004

str2num(t(:,2:end))
ans =

     2
     3
     4

First, we use textscan to read the data in as two strings and a float (could use other numerical formats. We have to open the file for reading first.

fid = fopen('myfile.txt');
A = textscan(fid,'%s%s%f');

textscan returns a cell array, so we have to extract your three variables. x and y are converted to single char arrays using cell2mat (works only if all the strings inside are the same length), n is a list of numbers.

x = cell2mat(A{1});
y = cell2mat(A{2});
n = A{3};

We can now convert x and y to numbers by telling it to take every row : but only the second to final part of the row 2:end, e.g 002, 003 , not b002, b003.

x = str2num(x(:,2:end));
y = str2num(y(:,2:end));

Slight problem with indexing - if I have a matrix A and I do this:

A = magic(8);
A([1,5],[3,8])

Then it returns four elements - [1,3],[5,3],[1,8],[5,8] - not two. But what you want is the location in your matrix equivalent to x(1),y(1) to be set to n(1) and so on. To do this, we need to 1) work out the final size of matrix. 2) use sub2ind to calculate the right locations.

% find the size
% if you have a specified size you want the output to be use that instead
xsize = max(x);
ysize = max(y);

% initialise the output matrix - not always necessary but good practice
out = zeros(xsize,ysize);

% turn our x,y into linear indices
ind = sub2ind([xsize,ysize],x,y);

% put our numbers in our output matrix
out(ind) = n;
分享给朋友:
您可能感兴趣的文章:
随机阅读: