简体   繁体   English

MATLAB-索引超出矩阵尺寸

[英]MATLAB - Index exceeds matrix dimensions

Hi I have problem with matrix.. 嗨,我有矩阵问题。

I have many .txt files with different number of rows but have the same number of column (1 column) 我有很多.txt文件,它们的行数不同,但是列数(1列)相同

e.g. s1.txt = 1234 rows
     s2.txt = 1200 rows
     s2.txt = 1100 rows

I wanted to combine the three files. 我想合并这三个文件。 Since its have different rows .. when I write it to a new file I got this error = Index exceeds matrix dimensions. 由于它具有不同的行..当我将其写入新文件时,出现此错误=索引超出矩阵尺寸。

How I can solved this problem? 我该如何解决这个问题? .

You can combine three matrices simply by stacking them: Assuming that s1 , etc are the matrices you read in, you can make a new one like this: 您可以简单地通过堆叠将三个矩阵组合在一起:假设s1等是您读入的矩阵,则可以像这样创建一个新矩阵:

snew = [s1; s2; s3];

You could also use the [] style stacking without creating the new matrix variable if you only need to do it once. 如果只需要执行一次,也可以使用[]样式堆栈而无需创建新的矩阵变量。

You have provided far too little information for an accurate diagnosis of your problem. 您提供的信息太少,无法准确诊断您的问题。 Perhaps you have loaded the data from your files into variables in your workspace. 也许您已将文件中的数据加载到工作区中的变量中。 Perhaps s1 has 1 column and 1234 rows, etc. Then you can concatenate the variables into one column vector like this: 也许s1有1列和1234行,依此类推。然后可以将变量连接成一个列向量,如下所示:

totalVector = [s1; s2; s3];

and write it out to a file with a save() statement. 并使用save()语句将其写到文件中。

Does that help ? 有帮助吗?

Let me make an assumption that this question is connecting with your another question , and you want to combine those matrices by columns, leaving empty values in columns with fewer data. 让我假设该问题与您的另一个问题有关 ,并且您希望按列组合这些矩阵,而在列中使用较少的数据保留空白值。

In this case this code should work: 在这种情况下,此代码应工作:

BaseFile ='s';
n=3;
A = cell(1,n);
for k=1:n
    A{k} = dlmread([BaseFile num2str(k) '.txt']);
end

% create cell array with maximum number of rows and n number of columns
B = cell(max(cellfun(@numel,A)),n); 

% convert each matrix in A to cell array and store in B
for k=1:n
    B(1:numel(A{k}),k) = num2cell(A{k});
end

% save the data
xlswrite('output.txt',B)

The code assumes you have one column in each file, otherwise it will not work. 该代码假定每个文件中都有一列,否则将无法工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM