How to solve pre-allocating array?
3 ビュー (過去 30 日間)
古いコメントを表示
Hello everyone,
I have a coding like this, where I need to extract the row which has same index number in column 5 of my data. Attached is my data,
%Example matrix
A = load('Ntxp0014.txt');
%Find indices to elements in first column of A that satisfy the equality
ind11 = A(:,5) == 11 ;
ind12 = A(:,5) == 12 ;
ind13 = A(:,5) == 13 ;
ind14 = A(:,5) == 14 ;
ind15 = A(:,5) == 15 ;
ind16 = A(:,5) == 16 ;
ind17 = A(:,5) == 17 ;
ind18 = A(:,5) == 18 ;
ind19 = A(:,5) == 19 ;
ind20 = A(:,5) == 20 ;
ind21 = A(:,5) == 21 ;
ind22 = A(:,5) == 22 ;
%Use the logical indices to index into A to return required sub-matrices
A11=A(ind11,:);
A12=A(ind12,:);
A13=A(ind13,:);
A14=A(ind14,:);
A15=A(ind15,:);
A16=A(ind16,:);
A17=A(ind17,:);
A18=A(ind18,:);
A19=A(ind19,:);
A20=A(ind20,:);
A21=A(ind21,:);
A22=A(ind22,:);
but it is not practical when deals with many data. How I would to solve this pre-allocating array? However, I've try using for ... end function but still have error.
%Example matrix
A = load('Ntxp0014.asc');
%Find indices to elements in first column of A that satisfy the equality
for i = 11:364
ind(i) = A(:,5) == i ;
%Use the logical indices to index into A to return required sub-matrices
A(i) = A(ind(i),:);
end
0 件のコメント
採用された回答
Stephen23
2020 年 1 月 18 日
編集済み: Stephen23
2020 年 1 月 18 日
Using numbered variables is a sign that you are doing something wrong.
Accessing numbered variables is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know why:
You can easily avoid that bad code approach by splitting that data into a cell array, either using a simple loop or some other grouping function, for example using arrayfun:
>> A = dlmread('Ntxp0014.txt'); % better than LOAD
>> V = 11:22;
>> F = @(n) A(A(:,5)==n,:);
>> C = arrayfun(F,V,'UniformOutput',false);
Lets check the contents of the first cell (fifth column==V(1)==11):
>> C{1}
ans =
1.9921e+013 1.84720 95.016 -36.904 11 14
1.9921e+013 1.79460 95.034 -36.599 11 14
1.9921e+013 1.74200 95.053 -36.346 11 14
1.9921e+013 1.68940 95.072 -36.130 11 14
1.9921e+013 1.63680 95.091 -35.879 11 14
... lots of lines
1.9921e+013 0.216460 95.597 -28.778 11 14
1.9921e+013 0.163860 95.616 -28.799 11 14
1.9921e+013 0.111250 95.635 -28.807 11 14
1.9921e+013 0.058644 95.653 -28.891 11 14
1.9921e+013 0.006037 95.672 -28.904 11 14
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!