How to fill array with value 0 if function returns empty []
조회 수: 27 (최근 30일)
이전 댓글 표시
I am creating a matrix for computing the natural frequency of beams with different boundary conditions. I have my assumed eigenfunction, I solve it at a boundary condition and then I want to collect all the terms attached to coefficients so I can collect thema ll and solve for the determinant which gives the characteristic equation to find the natural frequencies. However, the -C(T==c1)- terms return empty arrays which "disappear" when bringing them all together.
Is there an efficient way to replace these empty values with 0 as I show in the last line of my code?
I have tinkered around with cell arrays but they don't play nice with isempty without making loops.
syms x c1 c2 c3 c4 ki real
phi = c1*cos(ki*x) + c2*cosh(ki*x) + c3*sin(ki*x) + c4*sinh(ki*x);
phi_0 = simplify(subs( phi,x,0));
[C,T] = coeffs( phi_0,[c4 c3 c2 c1],'All'); %why is this backwards?
A = sym(zeros(4,4));
A(1,:) = [C(T==c1),C(T==c2),C(T==c3),C(T==c4)]; % Fails because RHS=[ki, ki] when it 'should' be [0, 0, ki, ki]
댓글 수: 0
채택된 답변
DGM
2022년 2월 21일
편집: DGM
2022년 2월 21일
I hardly ever use symbolic tools, so I'm sure someone knows a better way. Just paying attention to the output alone, this is one way to do it with cell arrays:
syms x c1 c2 c3 c4 ki real
phi = c1*cos(ki*x) + c2*cosh(ki*x) + c3*sin(ki*x) + c4*sinh(ki*x);
phi_0 = simplify(subs( phi,x,0));
[C,T] = coeffs( phi_0,[c4 c3 c2 c1],'All'); %why is this backwards?
% using a cell array
A = cell(4,4);
A(1,:) = {C(T==c1),C(T==c2),C(T==c3),C(T==c4)}
% after whatever loop ostensibly fills the rest of A
mask = cellfun(@isempty,A) % find empties
A(mask) = {sym(0)}; % replace with zero
A = reshape(vertcat(A{:}),4,4) % convert to sym array
추가 답변 (1개)
Bob Thompson
2022년 2월 21일
I admit I don't entirely understand the math here, so there may be a more elegant solution. My MATLAB access is also currently down, so nothing here has been tested.
That said, you could just use some logical indexing to find the empty values and replace them ahead of time.
syms x c1 c2 c3 c4 ki real
phi = c1*cos(ki*x) + c2*cosh(ki*x) + c3*sin(ki*x) + c4*sinh(ki*x);
phi_0 = simplify(subs( phi,x,0));
[C,T] = coeffs( phi_0,[c4 c3 c2 c1],'All'); %why is this backwards?
A = sym(zeros(4,4));
C(isempty(C)&T==c1) = 0; % Replace empty values with 0
A(1,:) = [C(T==c1),C(T==c2),C(T==c3),C(T==c4)]; % Fails because RHS=[ki, ki] when it 'should' be [0, 0, ki, ki]
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!