필터 지우기
필터 지우기

how to create a cell array with functions from a matrix consisting symbolic expression

조회 수: 2 (최근 30일)
I have a matrix A
clear all
clc
syms x y
A= [x x^2+y^2;x-y 2+y];
and I want to get a cell array like B; how do i get.. B needs to be a cell array with all elements having both x and y in their function handle regardless of the fact that wheather it is afunction of one variable only.
B = {@(x,y)x,@(x,y)x.^2+y.^2;@(x,y)x-y,@(x,y)x.^2-y.^2}
Thanks for your time and kind help

채택된 답변

Steven Lord
Steven Lord 2023년 4월 27일
Use arrayfun to call matlabFunction on each element of your symbolic array. In order for all the functions to have the same signature (the same input arguments) we need to precompute the list of variables used in expressions in A. The symvar function does that.
syms x y
A= [x x^2+y^2;x-y 2+y];
variablesInA = symvar(A)
variablesInA = 
c = arrayfun(@(z) matlabFunction(z, 'Vars', variablesInA), A, 'UniformOutput', false)
c = 2×2 cell array
{ @(x,y)x} {@(x,y)x.^2+y.^2} {@(x,y)x-y} { @(x,y)y+2.0}
To check, let's call some of the functions.
c{1, 2}(3, 4) % 3.^2+4.^2 is 25
ans = 25
c{2, 2}(Inf, 5) % 5 + 2 is 7, x is not used
ans = 7

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Assumptions에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by