How to fill array with value 0 if function returns empty []
28 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Sanders A.
el 21 de Feb. de 2022
Comentada: Sanders A.
el 22 de Feb. de 2022
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 comentarios
Respuesta aceptada
DGM
el 21 de Feb. de 2022
Editada: DGM
el 21 de Feb. de 2022
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
Más respuestas (1)
Bob Thompson
el 21 de Feb. de 2022
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]
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!