How to create array or table using for loop?

24 ビュー (過去 30 日間)
YE AUNG
YE AUNG 2019 年 9 月 12 日
コメント済み: YE AUNG 2019 年 9 月 12 日
Hello, I want to create a table or an array using for loop. What I want to do is something like running a function using the iteration numbers and i want to pring out both iteration numbers and the function in a table form or an array. For example:
for x = 1:64
for y = 1:64
for z = 1:64
f = 2*x + 2*y + z^2 (it's just an example, but some function like this)
end
end
end
I want to calculate the value of f at each iteration and print out all the values of x, y, z and the function f values either in a table or in an array like this
x y z f
1 1 1 5
2 2 2 12
3 3 3 21
4 4 4 32
and so on for all of them. How can i do that?
  1 件のコメント
David Hill
David Hill 2019 年 9 月 12 日
You likely will not need any loops at all. If you use the loops (as above), then you could have a matrix (F) that you should preallocate.
F=zeros(64^3,4);
count=1;
for x = 1:64
for y = 1:64
for z = 1:64
f = 2*x + 2*y + z^2 (it's just an example, but some function like this)
F(count,:)=[x,y,z,f];
count=count;
end
end
end

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

採用された回答

Walter Roberson
Walter Roberson 2019 年 9 月 12 日
f = zeros(64, 64, 64);
fidx = zeros(64, 64, 64, 3);
for x = 1:64
for y = 1:64
for z = 1:64
f(x,y,z) = 2*x + 2*y + z^2; %(it's just an example, but some function like this)
fidx(x,y,z,:) = [x, y, z];
end
end
end
x = reshape(fidx(:,:,:,1), [], 1);
y = reshape(fidx(:,:,:,2), [], 1);
z = reshape(fidx(:,:,:,3), [], 1);
f = f(:);
results = table(x, y, z, f);
However, you would be more likely to use a different approach:
[x, y, z] = ndgrid(1:64, 1:64, 1:64);
f = 2*x + 2*y + z.^2;
x = x(:);
y = y(:);
z = z(:);
f = f(:);
results = table(x, y, z, f);
  1 件のコメント
YE AUNG
YE AUNG 2019 年 9 月 12 日
Thank you.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangePerformance and Memory についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by