如何将文本字段读入MATLAB并创建一个矩阵 [英] How to read text fields into MATLAB and create a single matrix
问题描述
$ b
1,foo
2,bar
$ c
$ b 我试图用MatLab阅读这个:
A =的fopen( 'filename.csv');
B = textscan(A,'%d%d','delimiter',',');
C = cell2mat(B);
前两行工作正常,但问题是texscan不会创建2x2矩阵;而是创建一个1x2矩阵,每个值都是一个数组。所以我尝试使用最后一行将数组合并成一个大矩阵,但是它会产生一个错误,因为数组有不同的数据类型。
有没有办法获得围绕这个问题?或者更好的方法来组合数组?
解决方案确定是否合并是一个好主意。你可能会更好的与他们分开。
我改变了你的代码,以便它更好地工作:
clear
clc
A = fopen('filename.csv');
B = textscan(A,'%d%s','delimiter',',')
fclose(A)
观察结果
K >> B {1}
ans =
1
2
$ 2
$ b 'foo'
'bar'
真的,我认为这是最有用的格式。如果有的话,大多数人都希望将这个单元格数组分割成更小的块。
num = B {1}
txt = B {2}
为什么你想把它们合并?他们已经在一个单元格阵列中,这是你将得到最多的组合。
I have a huge CSV file that has a mix of numerical and text datatypes. I want to read this into a single matrix in Matlab. I'll use a simpler example here to illustrate my problem. Let's say I have this CSV file:
1,foo
2,bar
I am trying to read this into MatLab using:
A=fopen('filename.csv');
B=textscan(A,'%d %d', 'delimiter',',');
C=cell2mat(B);
The first two lines work fine, but the problem is that texscan doesn't create a 2x2 matrix; instead it creates a 1x2 matrix with each value being an array. So I try to use the last line to combine the arrays into one big matrix, but it generates an error because the arrays have different datatypes.
Is there a way to get around this problem? Or a better way to combine the arrays?
解决方案 I am note sure if combining them is a good idea. It is likely that you would be better off with them separate.
I changed your code, so that it works better:
clear
clc
A=fopen('filename.csv');
B=textscan(A,'%d %s', 'delimiter',',')
fclose(A)
Looking at the results
K>> B{1}
ans =
1
2
K>> B{2}
ans =
'foo'
'bar'
Really, I think this is the format that is most useful. If anything, most people would want to break this cell array into smaller chunks
num = B{1}
txt = B{2}
Why are your trying to combine them? They are already together in a cell array, and that is the most combined you are going to get.
这篇关于如何将文本字段读入MATLAB并创建一个矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!