How to create a matrix through a nested loop?

조회 수: 9 (최근 30일)
N/A
N/A 2022년 6월 6일
편집: Staff 34 2025년 10월 9일
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

답변 (1개)

Jan
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
N/A
N/A 2022년 6월 7일
편집: N/A 2022년 6월 7일
Thanks for the comment. I'm unforutnately getting this error- Unable to perform assignment because the indices on the left side are not compatible with the size of the right side—for the G_L_p_tot line. Why is this the case?
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.
Cheers
Jan
Jan 2022년 6월 7일
편집: Staff 34 2025년 10월 9일
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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by