フィルターのクリア

getting smaller arrays in sequence from a big array

4 ビュー (過去 30 日間)
Suleyman Deveci
Suleyman Deveci 2013 年 1 月 16 日
Hello all
I have an array which contains more than 1000 elements (lets say 'Array A'). I want to use this array to get smaller size arrays. For example 'Array 1' should include first 'n' elemets of the 'Array A' and 'Array 2' should include the next n elements of the 'Array A' and so on...
How can I do this with a for loop?
Thanks for the answers...
Regards
Suleyman

採用された回答

Pedro Villena
Pedro Villena 2013 年 1 月 16 日
A = randi(100,1,1000); %matrix of 1x1000
n = 100;
for i=1:floor(numel(A)/n),
eval(sprintf('A%d=A(%d:%d);',i,(i-1)*n+1,i*n));
end
  3 件のコメント
José-Luis
José-Luis 2013 年 1 月 16 日
編集済み: José-Luis 2013 年 1 月 16 日
eval is evil and you should try to avoid using it.
Jan
Jan 2013 年 1 月 16 日
編集済み: Jan 2013 年 1 月 16 日
eval is evil and you should avoid using it.
I've ommitted the "try to", because there is always a better method (except for one counter-example mentioned by Daniel).
There are many reasons to avoid eval and they are discussed frequently in this forum. There is no reason to create an indirekt method to create variables dynamically, if you need equivalent complicated and indirekt methods to access them later on.

サインインしてコメントする。

その他の回答 (2 件)

Jing
Jing 2013 年 1 月 16 日
Hi Suleyman,
There're many different ways to achieve what you want. I'm not sure what is the best one for your purpose, which depends on what kind of smaller arrays do you want. Following is my code, I prefer to use cell to store related arrays. A is the large array, and B has ten 10*10 array in it. You can index into B like B{2}(10,5), which is the A(10,15) originally.
A=rand(10,100);
n=10;
for i=1:(size(A,2)/n)
B{i}=A(:,(i-1)*n+1:i*n);
end

Jan
Jan 2013 年 1 月 16 日
If you have the data in one compact array, why do you want to split it into several arrays, which contain an index in the name of the variable? It is much more convenient and flexible to use another array, e.g. a cell.
A = rand(1000, 1);
n = 100;
B = reshape(A, n, []);
Now B(:, i) is what you call "Array 1".
If you really need a FOR loop, here an example with a cell:
n = 100;
Len = numel(A);
Num = ceil(Len / n);
B = cell(1, Num);
for ii = 1:Num
ini = 1 + (ii - 1) * n;
fin = min(ii * n, Len);
B{ii} = A(ini:fin);
end
  1 件のコメント
Suleyman Deveci
Suleyman Deveci 2013 年 1 月 16 日
Dear Jan, thank you for your reply. reshape function works well also for my case. I need use this arrays to produce some graphs, that is why I need to split the data.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by