How to create a matrix through a nested loop?
20 ビュー (過去 30 日間)
古いコメントを表示
Hi,
I have a nested loop which finds the sound pressure level in every position, given the distance from two speaker positions.
How do I make it so that, when ran, it doesnt create separate matrices, but one big matrix? Each x and y axis should cover 20 points (step-size of 0.5) so there should be 400 points on the matrix.
Thank you in advance!
stepsize = 0.5;
while i<=10
while j<=10
G_di1 = pdist([speaker1pos;[i,j]], 'euclidean');
G_di2 = pdist([speaker2pos;[i,j]],'euclidean');
G_Lp_y1 = L_w1 - 20*log10(G_di1) - 8;
G_Lp_y2 = L_w2 - 20*log10(G_di2) - 8;
G_L_p_tot = 10*log10(10.^(G_Lp_y1/10) + 10.^(G_Lp_y2/10));
j = j+stepsize;
end
j=0;
i=i+stepsize;
end
0 件のコメント
回答 (1 件)
Jan
2022 年 6 月 6 日
編集済み: Jan
2022 年 6 月 6 日
x = 1:0.5:10.5;
y = 1:0.5:10.5;
speaker1pos = [4.7, 2.3];
speaker2pos = [8.6, 4.8];
L_w1 = rand;
L_w2 = rand;
for j = 1:20
for i = 1:20
G_di1 = norm(speaker1pos - [y(j), x(i)]); % Easier than pdist
G_di2 = norm(speaker2pos - [y(j), x(i)]);
G_Lp_y1 = L_w1 - 20*log10(G_di1) - 8;
G_Lp_y2 = L_w2 - 20*log10(G_di2) - 8;
G_L_p_tot(i, j) = 10*log10(10^(G_Lp_y1/10) + 10^(G_Lp_y2/10));
end
end
Or without loops:
G_di1 = sqrt((speaker1pos(1) - x).^2 + (speaker1pos(2) - y.').^2);
G_di2 = sqrt((speaker2pos(1) - x).^2 + (speaker2pos(2) - y.').^2);
G_Lp_y1 = L_w1 - 20*log10(G_di1) - 8;
G_Lp_y2 = L_w2 - 20*log10(G_di2) - 8;
G_L_p_tot = 10*log10(10.^(G_Lp_y1/10) + 10.^(G_Lp_y2/10));
2 件のコメント
Jan
2022 年 6 月 7 日
編集済み: Staff 8
2025 年 10 月 9 日 18:48
This error is not produced by my code. Please post the code you are really using if you get an error message. Then post a copy of the complete message instead of selecting only some parts of it - the details matter.
Note that I had to invent some input data and guessed, that they are scalars. It would be more useful, if you post a working example, most of all if this detail produces the error.
"edit: I will also need to find a whole matrix of G_L_p_tot throughout the loop. I unfortunately have only been getting the last last iterations...this would help a lot, thank you so much."
I've posted 2 codes already to create the complete G_L_p_tot matrix, one with and another without a loop. Did you run my suggested codes?
参考
カテゴリ
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!