62visualizaciones (últimos 30días)
Mostrar comentarios más antiguos
Ammar el 11 de Jul. de 2024 a las 3:05
Comentada: Umar el 11 de Jul. de 2024 a las 4:46
Respuesta aceptada: Divyajyoti Nayak
Abrir en MATLAB Online
Hello,
I have a question about comparing values between elements of an array. I keep getting the error that says
Index exceeds the number of array elements. Index must not exceed 1.
I attached my code but I also put the section of the code I'm having an issue with.
See MATLAB code attached:
E_Plane.m
theta = 0:0.01:pi/2
% The size of theta is 1 x 315
% E_Plane_norm_dB is an array that is also 1 x 315 with numbers
%{
Essentially, I am trying to see which number in the E_Plane_norm_dB array is the closest to -3.
Whichever number is closest to -3, I would need to output the "theta" value
that corresponds to that number in E_Plane_norm_dB
The way I'm doing this is by finding the "distance" from that element to -3
I keep comparing the "distances" to -3 between each element, until I find
the "smallest distance". Whichever element in E_Plane_norm_dB has the
smallest "distance", I would like to output that "theta" value.
%}
% Solving for the theta angle.
for j = 1:length(theta)
loop_theta = theta(j);
distance(j) = E_Plane_norm_dB(j) - (-3);
if (distance(j) < distance(j+1:length(theta)))
theta_angle = loop_theta;
end
end
4 comentarios Mostrar 2 comentarios más antiguosOcultar 2 comentarios más antiguos
Mostrar 2 comentarios más antiguosOcultar 2 comentarios más antiguos
Umar el 11 de Jul. de 2024 a las 3:22
Enlace directo a este comentario
https://la.mathworks.com/matlabcentral/answers/2136388-comparing-difference-in-values-between-values-in-an-array-using-for-loop#comment_3208398
Hi Ammar,
The main cause of the error was the incorrect usage of indexing within the loop. The comparison distance(j) < distance(j+1:length(theta)) is not valid as it compares a single element to an array slice, leading to the index error. However, I have fixed and updated the code as listed below along with attached test results.
>> theta = 0:0.01:pi/2;
E_Plane_norm_dB = randn(size(theta)); % Example initialization
% Initialize variables to store the minimum distance and corresponding theta value
min_distance = inf;
theta_angle = 0;
% Iterate over each element in the arrays
for j = 1:length(theta)
% Calculate the distance from the current element to -3
current_distance = abs(E_Plane_norm_dB(j) - (-3));
% Check if the current distance is smaller than the minimum distance found so far
if current_distance < min_distance
% Update the minimum distance and corresponding theta value min_distance = current_distance; theta_angle = theta(j); endend
% Output the theta value corresponding to the element closest to -3
disp(['The theta value corresponding to the element closest to -3 is: ', num2str(theta_angle)]);
Attached result:
Please let me know if I can assist you further. Hope this will help resolve your problem.
VINAYAK LUHA el 11 de Jul. de 2024 a las 3:47
Enlace directo a este comentario
https://la.mathworks.com/matlabcentral/answers/2136388-comparing-difference-in-values-between-values-in-an-array-using-for-loop#comment_3208423
Editada: VINAYAK LUHA el 11 de Jul. de 2024 a las 4:43
Abrir en MATLAB Online
Hi Ammar,
As per the provided code, I understand that you are interested in finding the index of the element in array "E_Plane_norm_dB" which minimizes the difference "E_Plane_norm_dB - (-3);" and not the absolute distance as assumed in the previous comment, if this is the case, consider modifying your code as below-
differences = (E_Plane_norm_dB - (-3));
[~, index] = min(differences);
HPBW_Half_E=theta(index)
Thanks
Ammar el 11 de Jul. de 2024 a las 4:17
Enlace directo a este comentario
https://la.mathworks.com/matlabcentral/answers/2136388-comparing-difference-in-values-between-values-in-an-array-using-for-loop#comment_3208438
@Umar
Thank you for the response. Just to understand, why did you make the minimum distance infinity?
Umar el 11 de Jul. de 2024 a las 4:46
Enlace directo a este comentario
https://la.mathworks.com/matlabcentral/answers/2136388-comparing-difference-in-values-between-values-in-an-array-using-for-loop#comment_3208458
Hi Ammar,
Initializing the min_distance variable to inf (infinity) was to make sure that any calculated distance in the subsequent loop will be smaller than this initial value which will allow the comparison logic to correctly update the minimum distance as the loop progresses. Also,this approach guarantees that the initial distance comparison will always result in updating the minimum distance with the first calculated distance.
Iniciar sesión para comentar.
Iniciar sesión para responder a esta pregunta.
Respuesta aceptada
Divyajyoti Nayak el 11 de Jul. de 2024 a las 3:51
Editada: Divyajyoti Nayak el 11 de Jul. de 2024 a las 3:54
Abrir en MATLAB Online
Hi @Ammar, the reason you are getting an error is because the distance variable is not pre defined as a vector so it is not able to index from j+1 to length(theta). You can verify this by looking at the distance variable in the workspace.
distance(j) = E_Plane_norm_dB(j) - (-3); %distance is not the complete vector as it has only one element
if (distance(j) < distance(j+1:length(theta))) %distance cannot index into j+1 as distance(j+1) is not defined yet
theta_angle = loop_theta;
To fix your code you can pre-allocate the distance vector with the zeros function, like this:
distance = zeros(length(theta), 1);
Or, you can use MATLAB's vector manipulation to get the desired result instead of a for loop.
theta = 0.0.01:pi/2;
distances = E_Plane_norm_dB - (-3);
[~,idx] = min(abs(distances));
theta_angle = theta(idx);
1 comentario Mostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Mostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Ammar el 11 de Jul. de 2024 a las 4:25
Enlace directo a este comentario
https://la.mathworks.com/matlabcentral/answers/2136388-comparing-difference-in-values-between-values-in-an-array-using-for-loop#comment_3208443
Abrir en MATLAB Online
Hi @Divyajyoti Nayak
Thank You! The last section of code worked and gave the correct result.
theta = 0:0.01:pi/2;
distances = E_Plane_norm_dB - (-3);
[~,idx] = min(abs(distances));
theta_angle = theta(idx);
Iniciar sesión para comentar.
Más respuestas (0)
Iniciar sesión para responder a esta pregunta.
Ver también
Categorías
MATLABLanguage FundamentalsMatrices and ArraysMatrix Indexing
Más información sobre Matrix Indexing en Help Center y File Exchange.
Etiquetas
- comparing values
- arrays
- for loops
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
Se ha producido un error
No se puede completar la acción debido a los cambios realizados en la página. Vuelva a cargar la página para ver el estado actualizado.
Seleccione un país/idioma
Seleccione un país/idioma para obtener contenido traducido, si está disponible, y ver eventos y ofertas de productos y servicios locales. Según su ubicación geográfica, recomendamos que seleccione: .
También puede seleccionar uno de estos países/idiomas:
América
- América Latina (Español)
- Canada (English)
- United States (English)
Europa
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- Deutsch
- English
- Français
- United Kingdom(English)
Asia-Pacífico
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)
Comuníquese con su oficina local