# Force zeros to be be symbolic

8 views (last 30 days)

Show older comments

In the following code,

syms x y

f{1,1} = @(x,y) x+y

bad = 1;

if bad

f{1,2} = @(x,y) 0

else

f{1,2}=@(x,y) sym(0)

end

fMat = cellfun(@(z) feval(z,x,y),f)

the last line will throw an error.

The reason is that the first element of f is symbolic, but second is numeric, and cellfun doesn't like that.

A workaround is to change 0 to sym(0) as the example illustrates, when you set bad to 0.

Matlab's recommended solution is to add '

un',0

to the cellfun command. This works for this toy example, but in my complex application, 'un',0 creates all sorts of other problems.

My current code computes the matlab derivatives, and then, if they are zero, converts the 0's to sym(0) using strrep. This is incredibly awful and is likely to cause all sorts of problems in other settings.

The ideal solution for me would be to have the matlab symbolic diff command return everything as symbolic, including integers. Is there a way to impose that? Thanks for any suggestions.

##### 0 Comments

### Answers (2)

Walter Roberson
on 5 Jan 2022

"The reason I'm having problems is that I'm converting the output from diff to a character string and then writing it to a file. when I run the file"

Do not write it out plain. Write it out with a str2sym() wrapper. You need that anyhow in order to get constants back in with full accuracy.

You have another challenge as well: when you emit @(x,y)0 then you cannot integral() the handle. integral() requires that the output be the same size as the input but @(x,y)0 is scalar 0. To work with a constant C you need @(x,y)C*ones(size(x)) which is not something that matlabFunction() will emit automatically.

##### 3 Comments

Paul
on 5 Jan 2022

Edited: Paul
on 6 Jan 2022

Walter Roberson
on 5 Jan 2022

filename = fullfile(tempdir, 'test_str2sym.m');

syms x y

z = x + y

dz = diff(z,x)

d2z = diff(dz,x)

names_to_write = {'z', 'dz', 'd2z'};

vars_to_write = {z, dz, d2z};

fid = fopen(filename, 'w');

for K = 1 : length(names_to_write)

fprintf(fid, "%s = str2sym('%s');\n", names_to_write{K}, char(vars_to_write{K}));

end

fclose(fid)

type(filename)

clearvars x y z dz d2z

addpath(fileparts(filename));

test_str2sym();

whos

z

dz

d2z

Paul
on 5 Jan 2022

I'm not familiar with this?

un',0

Can you show that in a cellfun command?

In any case, diff() always returns a symbolic expression, doesn't it? (though the doc page does even have an Output section that says so explicitly).

syms x

d1 = diff(3*x)

d2 = diff(0*x)

whos

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!