Comparing difference in values between values in an array - Using F... (2024)

62visualizaciones (últimos 30días)

Mostrar comentarios más antiguos

Ammar el 11 de Jul. de 2024 a las 3:05

  • Enlazar

    Enlace directo a esta pregunta

    https://la.mathworks.com/matlabcentral/answers/2136388-comparing-difference-in-values-between-values-in-an-array-using-for-loop

  • Enlazar

    Enlace directo a esta pregunta

    https://la.mathworks.com/matlabcentral/answers/2136388-comparing-difference-in-values-between-values-in-an-array-using-for-loop

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

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

  • Enlazar

    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:

Comparing difference in values between values in an array - Using F... (3)

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

  • Enlazar

    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

  • Enlazar

    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

  • Enlazar

    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

  • Enlazar

    Enlace directo a esta respuesta

    https://la.mathworks.com/matlabcentral/answers/2136388-comparing-difference-in-values-between-values-in-an-array-using-for-loop#answer_1484048

  • Enlazar

    Enlace directo a esta respuesta

    https://la.mathworks.com/matlabcentral/answers/2136388-comparing-difference-in-values-between-values-in-an-array-using-for-loop#answer_1484048

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

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

  • Enlazar

    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.


Translated by Comparing difference in values between values in an array - Using F... (9)

Comparing difference in values between values in an array - Using F... (10)

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

Comparing difference in values between values in an array - Using F... (2024)

References

Top Articles
Pokémon GO Spotlight Hour Times: This Week's Featured Pokémon And Mystery Bonus - 16th July 2024
Resource - ZU Old Gens Hub - ADV Aipom ban #337
Swissport Timecard
Extranet Landing Page Delta
Stayton Craigslist
Ucsf Ilab
Petco Westerly Ri
Minus8 Patreon
Can ETH reach 10k in 2024?
Evil Dead Rise Showtimes Near Amc Antioch 8
Best Taq 56 Loadout Mw2 Ranked
24/7 Walmarts Near Me
Memphis Beauty 2084
Espn Major League Baseball Standings
B Corp: Definition, Advantages, Disadvantages, and Examples
Jennifer Lenzini Leaving Ktiv
Claims Adjuster: Definition, Job Duties, How To Become One
The Woman King Showtimes Near Cinemark 14 Lancaster
M3Gan Showtimes Near Regal City North
Ds Cuts Saugus
Comenity Pay Cp
12 Week Glute Program to Transform Your Booty with Free PDF - The Fitness Phantom
Shs Games 1V1 Lol
PoE Reave Build 3.25 - Path of Exile: Settlers of Kalguur
Vilonia Treasure Chest
Kawasaki Ninja® 500 | Motorcycle | Approachable Power
Dtm Urban Dictionary
3 30 Mountain Time
Staar English 2 2022 Answer Key
Hartford Healthcare Employee Tools
Sams Gas Price Garland Tx
Worldfree4U In
Restored Republic June 16 2023
Bdo Passion Of Valtarra
8004966305
Craiglist.nj
Artifacto The Ascended
4156303136
Christian Publishers Outlet Rivergate
Horoscope Today: Astrological prediction September 9, 2024 for all zodiac signs
Dust Cornell
CareCredit Lawsuit - Illegal Credit Card Charges And Fees
Alt J Artist Presale Code
5417873087
C And B Processing
2-bedroom house in Åkersberga
Experity Installer
Plusword 358
Skip The Games Mil
'Selling Sunset' star Alanna Gold said she owned a California desert town. Now, she says she doesn't.
Erfolgsfaktor Partnernetzwerk: 5 Gründe, die überzeugen | SoftwareOne Blog
South Florida residents must earn more than $100,000 to avoid being 'rent burdened'
Latest Posts
Article information

Author: Jerrold Considine

Last Updated:

Views: 6671

Rating: 4.8 / 5 (58 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.