Used str2num but the result is string.
Afficher commentaires plus anciens
I used str2num to convert string to numeric value but it did not. Any suggeston why?
for jjj=1:length(struct)
splitparam=regexp(struct(jjj).name,'\_','split');
if size(splitparam,2)==2
k_name(jjj)=string(cell2mat(splitparam(1,1)));
k_value(jjj)=str2num(cell2mat(splitparam(1,2)));
elseif (size(splitparam,2)==3)
k_name(jjj)=string(strcat(cell2mat(splitparam(1,1)),'_',cell2mat(splitparam(1,2))));
k_value(jjj)=str2num(cell2mat(splitparam(1,3)));
end
end

6 commentaires
"Any suggeston why?"
Most likely because you loop did not run, or none of the if conditions were true. But as you did not upload any data, we have no meaningful way to run your code and debug it for you.
Note that str2double is preferred over str2num.
Note that rather than this complex code using superfluous cell2mat
cell2mat(splitparam(1,1))
you can simply use the cell indexing:
splitparam{1}
Zeynab Mousavikhamene
le 16 Oct 2019
Zeynab Mousavikhamene
le 16 Oct 2019
"I used str2double and it did the same and produced the string."
Did I write that str2double would fix your problem? (hint: no). I advised you to use str2double because it avoids the pitfalls of eval, which is hidden inside str2num, not because it will solve your problem. If it would solve your problem, I would have given that as an answer.
Neither str2double nor str2num output strings or character vectors. The problem is caused by:
- those commands are not being run at all, or
- the data is being replaced again afterwards, or
- something else...
but without having data to run your code on, we can only guess. If you want further help with this, please upload some sample data by clicking the paperclip button.
Walter Roberson
le 17 Oct 2019
The posted code does not create a table. The construction of the table could be the problem
Guillaume
le 17 Oct 2019
Actually, according to the screenshot, the table data appears to be string arrays, in which case rather than str2num and str2double, simply use double:
>> double(["123", "456.78"])
ans =
123 456.78
The naming of variables in the given code snippet is appaling. Naming a variable struct is a very bad idea since it will prevent the creation of structure and a better name than the very unimaginative jjj would be advised.
In any case, it would seem that the problem with k_value is that it has been imported incorrectly as a string array. Modifying the import code so that it's imported directly as numbers would be the best course of action, rather than fixing the mess after the fact. To help with that we need an example of the source file (as an attachment).
Réponses (0)
Catégories
En savoir plus sur Data Type Conversion dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!