필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
Benjamin Karlsen
Benjamin Karlsen 2019년 3월 14일
댓글: Benjamin Karlsen 2019년 3월 15일
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{:})
Benjamin Karlsen
Benjamin Karlsen 2019년 3월 15일
thanks! helpfull

댓글을 달려면 로그인하십시오.

추가 답변 (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