How to use array indexing with input dialog
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Levente Gellért
le 21 Juin 2024
Commenté : Pavan Sahith
le 6 Août 2024
Dear MatLab Community, I am trying to use input dialog for indexing my array. The indexing is not a problem with numbers, however, when I try to give 1:end as default answer, the behavior of str2double I do not understand, and it does not work for me.
Any suggestions are highly appreciated.
Thank you
lg
e.g
a=1:100;
prompt = {'Enter timeframe:'};
dlg_title = 'Input';
num_lines = 1;
defaultans = {'1:end'};
answer = inputdlg(prompt,dlg_title,num_lines,defaultans);
a=a(1,str2double(answer{1, 1}));
so, how to use 1:end or something:something in the input dialog to get the wished length of variable a?
1 commentaire
Réponse acceptée
Pavan Sahith
le 21 Juin 2024
Modifié(e) : Pavan Sahith
le 21 Juin 2024
Hello Leventte,
I see that you are encountering issues when trying to accept expressions like 1:end from an input dialog in MATLAB.
The str2double function is designed to convert strings to numeric values and doesn't interpret MATLAB expressions like 1:end. To handle this, you can use eval to evaluate the input string as a MATLAB expression.
I assume your usecase is to fetch array indices from the input dialog , so you can refer to this sample code to understand the usage of eval
a = 1:100;
prompt = {'Enter timeframe:'};
dlg_title = 'Input';
num_lines = 1;
defaultans = {'1:end'};
answer = inputdlg(prompt, dlg_title, num_lines, defaultans);
% Check if the user provided an input
if ~isempty(answer)
try
% Evaluate the indexing expression
indexExpression = answer{1};
index = eval(['a(' indexExpression ')']);
disp('Indexed values:');
disp(index);
catch ME
% Handle any errors that occur during evaluation
disp('Error evaluating indexing expression:');
disp(ME.message);
end
else
disp('No input provided.');
end
you can refer to the following MathWorks documentation to know more about
Hope this helps you getting started
2 commentaires
Ganesh
le 21 Juin 2024
@Levente Gellért, you should also be aware of the risks with using "eval()"
Pavan Sahith
le 6 Août 2024
yeah true, using eval in MATLAB can pose significant security risks, especially when dealing with untrusted input.
To mitigate these risks, one of the way is to combine try-catch blocks with input validation, as demonstrated in the code above.
Additionally, you can explore safer alternatives to eval.
Alternatives to the eval Function: https://www.mathworks.com/help/matlab/matlab_prog/string-evaluation.html
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!