Filter löschen
Filter löschen

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

1 Ansicht (letzte 30 Tage)
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 Kommentare
Stephen23
Stephen23 am 14 Mär. 2019
Bearbeitet: Stephen23 am 14 Mär. 2019
"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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Bob Thompson
Bob Thompson am 14 Mär. 2019
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 Kommentare
Stephen23
Stephen23 am 14 Mär. 2019
Bearbeitet: Stephen23 am 14 Mär. 2019
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{:})

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by