Force zeros to be be symbolic
19 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Walter Roberson
2022-1-5
"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 个评论
Paul
2022-1-5
编辑:Paul
2022-1-6
I can't speak for @Walter Roberson, but it may be helpful to show what what you're actually doing, i.e., what is being written to the file and what you intend to do with the file after it's written.
Walter Roberson
2022-1-5
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
2022-1-5
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!