A problem with a code that works as it is but gives an index error ... (2024)

17 visualizzazioni (ultimi 30 giorni)

Mostra commenti meno recenti

Itay il 17 Lug 2024 alle 13:20

  • Link

    Link diretto a questa domanda

    https://it.mathworks.com/matlabcentral/answers/2138072-a-problem-with-a-code-that-works-as-it-is-but-gives-an-index-error-when-is-used-inside-a-function

  • Link

    Link diretto a questa domanda

    https://it.mathworks.com/matlabcentral/answers/2138072-a-problem-with-a-code-that-works-as-it-is-but-gives-an-index-error-when-is-used-inside-a-function

Risposto: Voss il 17 Lug 2024 alle 14:57

Apri in MATLAB Online

Hi,

I am writting a code that basically reads force curves from my microscope and then auto-align them based on their baseline and the offset. After it does it, I then divide the data into 30 graphs blocks so that I can remove bad curves. I basically 113 curves so there are 4 blocks where the last block has only 23 curves.

The problem is that when I run the code by itself it works perfectly. However when I put it inside a function, I am getting when it enter the 4th block the following error message: "Index in position 2 exceeds array bounds. Index must not exceed 100. Error in cleaner (line 118) z_corrj = z_corr(:, j);" - I just can't understand why it works perfectly but crashes when it is part of the function.

Here is the original code:

block_size = 30;

% Calculate the number of blocks

num_blocks = ceil(size((d_corr),1) / block_size)

% Loop through each dataset

for i = 1:num_blocks

figure;

hold on;

start_idx = (i-1) * block_size + 1;

end_idx = min(i*block_size, size((d_corr),1));

% Extract the i-th column for X and Y

for j = start_idx:end_idx

z_corrj = z_corr(:, j);

d_corrj = d_corr(:, j);

Zj = ones(size(z_corrj)) * j;

% Plot using plot3

plot3(z_corrj, d_corrj, Zj);

end

% Customize the plot

xlabel('Z [nm]');

ylabel('Deflection [V]');

zlabel('Index');

title('3D Plot of 10 XY sets');

grid on;

% Set the view orientation

azimuth = 117.4; % Azimuth angle in degrees

elevation = 50; % Elevation angle in degrees

view(azimuth, elevation);

hold off;

%Remove bad curves

trash = 0;

trash = input('If you want to remove a curve, input its number x (press Enter if you are done): ');

if trash

z_corr(:,trash) = [];

d_corr(:,trash) = [];

else

end

if i<num_blocks

disp('Press Enter to display the next block') ;

pause;

end

end

0 Commenti

Mostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Accedi per rispondere a questa domanda.

Risposte (1)

Voss il 17 Lug 2024 alle 14:57

  • Link

    Link diretto a questa risposta

    https://it.mathworks.com/matlabcentral/answers/2138072-a-problem-with-a-code-that-works-as-it-is-but-gives-an-index-error-when-is-used-inside-a-function#answer_1486907

Apri in MATLAB Online

Based on the error message, "Index in position 2 exceeds array bounds. Index must not exceed 100. Error in cleaner (line 118) z_corrj = z_corr(:, j);" we know that z_corr has 100 columns. And since you say you have 113 curves, I'll assume that each curve corresponds to a row of z_corr, so that z_corr has 113 rows. I'll also assume d_corr and z_corr have the same size.

If those assumptions are correct, then the problem is that you are taking the jth column of z_corr and d_corr here

z_corrj = z_corr(:, j);

d_corrj = d_corr(:, j);

when you should be taking the jth row

z_corrj = z_corr(j, :);

d_corrj = d_corr(j, :);

because curves correspond to rows. Your num_blocks and end_idx are based on the number of rows of d_corr (size(d_corr,1)), so you need to take a row from each matrix, not a column.

Making that change (and also commenting out the user-interaction section for running in this environment - and fixing the plot titles to correctly indicate the number of curves while I'm at it) the code runs without error, using random 113-by-100 matrices for d_corr and z_corr:

d_corr = rand(113,100);

z_corr = rand(113,100);

block_size = 30;

% Calculate the number of blocks

num_blocks = ceil(size((d_corr),1) / block_size)

num_blocks = 4

% Loop through each dataset

for i = 1:num_blocks

figure;

hold on;

start_idx = (i-1) * block_size + 1;

end_idx = min(i*block_size, size((d_corr),1));

% Extract the j-th row for X and Y

for j = start_idx:end_idx

z_corrj = z_corr(j, :);

d_corrj = d_corr(j, :);

% Assign a constant Z value for this dataset

Zj = ones(size(z_corrj)) * j;

% Plot using plot3

plot3(z_corrj, d_corrj, Zj);

end

% Customize the plot

xlabel('Z [nm]');

ylabel('Deflection [V]');

zlabel('Index');

title(sprintf('3D Plot of %d XY sets',end_idx-start_idx+1));

grid on;

% Set the view orientation

azimuth = 117.4; % Azimuth angle in degrees

elevation = 50; % Elevation angle in degrees

view(azimuth, elevation);

hold off;

% %Remove bad curves

% trash = 0;

% trash = input('If you want to remove a curve, input its number x (press Enter if you are done): ');

% if trash

% z_corr(:,trash) = [];

% d_corr(:,trash) = [];

% else

%

% end

% if i<num_blocks

% disp('Press Enter to display the next block') ;

% pause;

% end

end

A problem with a code that works as it is but gives an index error ... (3)

A problem with a code that works as it is but gives an index error ... (4)

A problem with a code that works as it is but gives an index error ... (5)

A problem with a code that works as it is but gives an index error ... (6)

0 Commenti

Mostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Accedi per rispondere a questa domanda.

Vedere anche

Tag

  • index error message

Community Treasure Hunt

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

Start Hunting!

Si è verificato un errore

Impossibile completare l'azione a causa delle modifiche apportate alla pagina. Ricarica la pagina per vedere lo stato aggiornato.


Translated by A problem with a code that works as it is but gives an index error ... (7)

A problem with a code that works as it is but gives an index error ... (8)

Seleziona un sito web

Seleziona un sito web per visualizzare contenuto tradotto dove disponibile e vedere eventi e offerte locali. In base alla tua area geografica, ti consigliamo di selezionare: .

Puoi anche selezionare un sito web dal seguente elenco:

Americhe

  • 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-Pacifico

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本Japanese (日本語)
  • 한국Korean (한국어)

Contatta l’ufficio locale

A problem with a code that works as it is but gives an index error ... (2024)

FAQs

What type of error is an index error? ›

An IndexError means that your code is trying to access an index that is invalid. This is usually because the index goes out of bounds by being too large. For example, if you have a list with three items and you try to access the fourth item, you will get an IndexError.

Why am I getting an index error? ›

The ultimate cause of IndexError is an attempt to access an item that doesn't exist within a data structure.

What is index of error? ›

The "Index of /" error occurs when no index file exists on your website directory or root folder. To fix this error, you can edit your . htaccess file by disabling the directory listing or checking your index file.

What is index error in Python code? ›

The IndexError: list index out of range error occurs in Python when an item from a list is attempted to be accessed that is outside the index range of the list. The range of a list in Python is [0, n-1], where n is the number of elements in the list.

What are the three 3 types of errors? ›

There are three types of errors that are classified based on the source they arise from; They are:
  • Gross Errors.
  • Random Errors.
  • Systematic Errors.

What are indexing errors? ›

Not found (404), or a broken URL, is probably one of the most common indexing issues. A page may have a 404 status code for many reasons. Say, you have deleted the URL but did not remove the page from the sitemap, written the URL incorrectly, etc.

What is an index problem? ›

The index number problem is the term used by economists to describe the limitation of statistical indexing, when used as a measurement for cost-of-living increases. For example, in the Consumer Price Index, a reference year's "market basket" is assigned an index number of 100.

Is an index error a runtime error? ›

Another common example of a runtime error in Python is an index error. This error occurs when you try to access an index of a list or tuple that is out of range.

Is an index error an exception? ›

In Python, the IndexError is a common exception that occurs when trying to access an element in a list, tuple, or any other sequence using an index that is outside the valid range of indices for that sequence.

How will you determine index error? ›

b) Index Error:

To find the index error, by day, using the horizon, clamp the index bar at zero and holding the sextant vertically, view the horizon through the telescope. If the true horizon and its reflection appear in the same line, Index error is not present.

How do I fix an index out of bound error? ›

Here are some steps to resolve the exception:
  1. Review the code to find the line that triggered the exception. ...
  2. Check the values used for index variables and ensure they are within the valid range.
  3. Implement proper index validation to prevent the exception from occurring in the future.
Oct 27, 2023

What is the difference between key error and index error? ›

Containers like lists and dictionaries will generate errors if you try to access items in them that do not exist. For lists, this type of error is called an IndexError ; for dictionaries, it is called a KeyError . Trying to read a file that does not exist will give you an IOError .

What are the 3 errors in Python? ›

There are three basic types of errors that programmers need to be concerned about: Syntax errors, runtime errors, and Logical errors.

What is index in Python coding? ›

In Python, indexing refers to the process of accessing a specific element in a sequence, such as a string or list, using its position or index number. Indexing in Python starts at 0, which means that the first element in a sequence has an index of 0, the second element has an index of 1, and so on.

How do you fix a value error in Python? ›

To resolve the ValueError in Python code, a try-except block can be used. The lines of code that can throw the ValueError should be placed in the try block, and the except block can catch and handle the error.

What type of error is index out of bounds? ›

The Index Out of Bounds Exception is a common issue in Java that occurs when trying to access elements at invalid indices in arrays, lists, or other data structures. Understanding its causes, effects, and implementing best practices can help you prevent this exception and write more reliable and robust Java code.

What type of error is a value error? ›

The Python ValueError is an exception that occurs when a function receives an argument of the correct data type but an inappropriate value. This error usually occurs in mathematical operations that require a certain kind of value.

Top Articles
Latest Posts
Article information

Author: Nathanael Baumbach

Last Updated:

Views: 6160

Rating: 4.4 / 5 (75 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Nathanael Baumbach

Birthday: 1998-12-02

Address: Apt. 829 751 Glover View, West Orlando, IN 22436

Phone: +901025288581

Job: Internal IT Coordinator

Hobby: Gunsmithing, Motor sports, Flying, Skiing, Hooping, Lego building, Ice skating

Introduction: My name is Nathanael Baumbach, I am a fantastic, nice, victorious, brave, healthy, cute, glorious person who loves writing and wants to share my knowledge and understanding with you.