Help with Code Problem

for k=1:0.1:5;
eval(['HT_' num2str(k) '=H;']);
end
This code works for odd numbers(ie 1,2,3,etc) but it wont work with decimal numbers(i.e 1.1,1.2, etc). Its giving an error every time I try. Can anyone please come to rescue? Thanks in advance.

4 comentarios

Stephen23
Stephen23 el 25 de Mzo. de 2016
Editada: Stephen23 el 25 de Mzo. de 2016
The awful eval strikes again.
By choosing to use eval you write buggy code. This is classic example of bad code causing pointless problems that could be avoided by simply avoiding eval. The problem is that you are trying to generate an invalid variable name. However because you used the awful eval MATLAB cannot tell you exactly where this error occurs, because by using eval you have removed all of the very useful code checking and code helper tools that MATLAB has built in. This is like driving blindfolded. You are a beginner, why do you pick the one function that makes programming more difficult?
Learn to program properly without eval and you will never have these kind of difficult to debug problems which give obscure error messages. Because when you program properly (without eval|), MATLAB actually helps you and gives code hints and checks your code as you write it.
Don't create numbered variables. Use a cell array. Or a numeric array. Or structure. And then learn about indexing.
Bilal Bingolbali
Bilal Bingolbali el 25 de Mzo. de 2016
Yeah I am new to Matlab and as of now I aint got any other option apart from eval code...what do u suggest I do?.Thanx angain.
Walter Roberson
Walter Roberson el 25 de Mzo. de 2016
If it worked, what would you like the result to be for k = 1.2 (for example) ?

Iniciar sesión para comentar.

Respuestas (1)

Star Strider
Star Strider el 25 de Mzo. de 2016

1 voto

All that said, if you want decimals from num2str, you have to specify a format descriptor:
num2str(k, '%3.1f')
That will work, although I have no idea if it will work in the code you posted.
There is a legitimate reasons to use eval, the most significant being that you have a series of dynamically-created variables that you did not yourself create and that you are saving to a matrix in order to correct the original error in creating them, but beyond that dynamically-created variables are to be avoided.

Categorías

Productos

Etiquetas

Preguntada:

el 25 de Mzo. de 2016

Editada:

el 15 de Feb. de 2022

Community Treasure Hunt

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

Start Hunting!

Translated by