Naming new sets of data in for loop and dividing matrixes.

1 次查看(过去 30 天)
Hi,
My goal is to divide a 42x525 matrix into 21 42x25 matrixes.
I have 21 sets of data which I have uploaded into matlab in a short for loop
for p = -10:10
filename = strcat('meanfile',num2str(p),'.txt');
line{p+11}=dlmread(filename,'\t',0,0) ;
end
Each data set contain 25 columns and 42 rows, where there are either 18, 32 or 42 rows that have non zero values.
My first code snip made a 1 by 21 cell array where each cell contained a 42x25 matrix. Now to get these into numbers I did a short
for p = 1:21
A = cell2mat(line);
end
This turned by data into a 42x525 matrix. Now what I really want is to divide these into 21 matrixes in a for loop.
I tried something like
for i = 1:21
strcat('line',num2str(i)) = A(1:end,(1:25)*i)
end
however this does not seem to work.
It might be confusing that the lines that are loaded are named from line-10 to line10 and in matlab I try to name them from line 1 to 21, but that is just to avoid non positive integers in the {}.
  3 个评论
Stephen23
Stephen23 2019-3-14
编辑:Stephen23 2019-3-14
"Now what I really want is to divide these into 21 matrixes in a for loop."
Do NOT do this. Dynamically accessing variable names is one way that beginners froce themselves into writing slow, complex, obfuscated, buggy code that is hard to ddebug. Read this to know some of the reasons why:
You can trivially use indexing, e.g. with a cell array or an ND array. Indexing is simple, neat, and very efficient, unlike what you are trying to do.
"My goal is to divide a 42x525 matrix into 21 42x25 matrixes."
You can do this easily with just one mat2cell call.

请先登录,再进行评论。

采纳的回答

Bob Thompson
Bob Thompson 2019-3-14
Why not just load the data into a third dimension from the beginning?
for p = -10:10
filename = strcat('meanfile',num2str(p),'.txt');
line(:,:,p+11)=dlmread(filename,'\t',0,0) ;
end
  3 个评论
Stephen23
Stephen23 2019-3-14
编辑:Stephen23 2019-3-14
A robust alternative is to load into a cell array (as the MATLAB documentation shows), and then concatenate it together after the loop:
V = -10:10;
N = numel(V);
C = cell(1,N);
for k = 1:N
F = sprintf('meanfile%d.txt',V(k));
C{k} = dlmread(F,'\t',0,0);
end
A = cat(3,C{:})

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by