Saving data from nested for loop

16 ビュー (過去 30 日間)
Maaz Madha
Maaz Madha 2020 年 3 月 17 日
コメント済み: Maaz Madha 2020 年 3 月 18 日
Hi
I want to store data from a nested for loop and this is my code
%%Initialisation 1
delta_x=(2*pi)/100;
delta_y=delta_x;
H=2*pi;
L=4*pi;
%Mesh
n=(L/delta_x)+1; Converts rectangle to a mesh
m=(H/delta_y)+1;
x=[0:delta_x:n]';
y=[0:delta_y:m]';
for i=x(2):delta_x:x(end-1)
for j=y(2):delta_y:y(end-1)
pointer=[(j-1)*n+i];
end
end
Everytime the pointer runs it only gives me the latest iteration and not all the iterations like I want. I tried putting (i,j) before it but that was to no avail and now am at my wits end as to what to do. Any help would be much appreciated

採用された回答

Adam Danz
Adam Danz 2020 年 3 月 17 日
編集済み: Adam Danz 2020 年 3 月 17 日
Give this a shot. It's usually best to set up for-loops to iterate over integer values 1 to n. Those integer values can be used to index input values and store the outputs.
iLoop = x(2):delta_x:x(end-1);
jLoop = y(2):delta_y:y(end-1);
pointer = nan(numel(iLoop), numel(jLoop));
for i = 1:numel(iLoop)
for j = 1:numel(jLoop)
pointer(i,j)=(jLoop(j)-1)*n+iLoop(i);
end
end
  3 件のコメント
Adam Danz
Adam Danz 2020 年 3 月 18 日
Good question!
This is known as preallocation. My example shows how to store scalar outputs (single value) at location (i,j) in variable 'pointer'. Instead of building that matrix as the loops iterate, the matrix is created with NaN values prior to the loops. This makes the code faster and cleaner.
The numel() function just returns the number of elements of a vector.
Maaz Madha
Maaz Madha 2020 年 3 月 18 日
aah i understand now. Thank you so very much :) have a great day

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by