obtaining an array containing arrays

hello, suppose i am generating an array with every loop. I want a new array to store all the values of the array together but seperately as different elements. If I have A = [1 2 3 4] in the 1st loop and A = [2 4 6 8] when it completes the second loop i want an array B that will have B= [1 2 3 4 ; 2 4 6 8]. If anyone can help me with this, I will be grateful. Thank you.

 採用された回答

James Tursa
James Tursa 2017 年 6 月 20 日
編集済み: James Tursa 2017 年 6 月 20 日

2 投票

E.g.,
m = number of loop iterations
B = zeros(m,4);
for k=1:m
A = results of current iteration
B(k,:) = A;
end

4 件のコメント

Jan
Jan 2017 年 6 月 20 日
:-) Obviously the solution is obvious. +1
shru s
shru s 2017 年 6 月 20 日
Thank you so much for the help. If i don't know that the array will contain 4 elements beforehand, how should i go about it?
James Tursa
James Tursa 2017 年 6 月 20 日
編集済み: James Tursa 2017 年 6 月 20 日
You could set things up so the first iteration expands the matrix appropriately. E.g.,
m = number of loop iterations
B = zeros(m,0); % <-- Unknown column size, so start with 0
for k=1:m
A = results of current iteration
B(k,1:size(A,2)) = A; % <-- 1st iteration will set the column size
end
shru s
shru s 2017 年 6 月 22 日
Thank you so much for your help!

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

その他の回答 (1 件)

Jan
Jan 2017 年 6 月 20 日
編集済み: Jan 2017 年 6 月 20 日

1 投票

nLoop = 5;
nValue = 4;
Result = zeros(nLoop, nValue); % Pre-allocate!
for k = 1:nLoop
A = randi(10, 1, nValue) % Example data
Result(k, :) = A;
end
disp(Result)

3 件のコメント

shru s
shru s 2017 年 6 月 20 日
thank you! but if i cannot determine nValue beforehand, how should I go about it?
Jan
Jan 2017 年 6 月 20 日
編集済み: Jan 2017 年 6 月 20 日
See James' answer. If nValue i changing between the elements, use a cell array:
nLoop = 5;
Result = cell(nLoop, 1); % Pre-allocate!
for k = 1:nLoop
A = randi(10, 1, randi(5)) % Example data
Result{k} = A;
end
An "implicite pre-allocation" works also, if you create the last element at first:
nLoop = 5;
for k = nLoop:-1:1 % Backwards for implicite pre-allocation
A = randi(10, 1, 4) % Example data
Result(k, :) = A;
end
It is essential, that the output does not grow iteratively, because this requires an exponentially growing number of resources. With 5 iterations this cannot be measured, but the rule is to care about a pre-allocation in general as a good programming practice.
shru s
shru s 2017 年 6 月 22 日
thank you so much for helping me out :)

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2017 年 6 月 20 日

コメント済み:

2017 年 6 月 22 日

Community Treasure Hunt

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

Start Hunting!

Translated by