shshchch88
shshchch88

Reputation: 453

MATLAB num2str format

I'm storing variable values in MATLAB and putting one of the variable values as part of the file name . e.g. "Error=1e-003.mat", however different version of MATLAB gives me different format when I'm converting numbers to string using num2str command. The number 1e-3, MATLAB2011 gives me 1e-003 and MATLAB2012 gives me 1e-03.

This runs into trouble when I try to load a batch of files with a mix of those two format. Does anyone know a way to add a zero or delete a zero for the exponent so the names are consistent? Or any other ways to solve this problem?

Upvotes: 4

Views: 2964

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

Here's a fairly robust way to do it:

A = num2str(YOUR_NUMBER, '%0.0e');

if A(end-2)=='-' || A(end-2)=='+'
    A = [A(1:end-2) '0' A(end-1:end)]; end

In words: convert the number, and check if the second-to-last character is either a '+' or a '-'. If this is so, add a '0'.

Upvotes: 1

user930916
user930916

Reputation: 421

Specify a "Format string as the second argument like this:

>> disp(num2str(2920230,'%0.10e'))
2.9202300000e+006

here %0.10e means display at least 0 digits before decimal and exactly 10 digits after it in exponent form.

Upvotes: -1

Related Questions