# How do I delete cell elements from a cell array?

3 views (last 30 days)
Shahriyar Karim on 6 Mar 2020
Answered: BobH on 14 Mar 2020
My function is supposed to take in an Nx3 cell array of unknown variables and known parameters and output an Nx2 cell array of unknown variable and respective value.
The first column corresponds to K values, second to m, and third column to v
I am to use K=(.5)mv^2 to find each unknown
Example:
hw_i = [{'K'} {} {}
{} {} {'v'}
{} {'m'} {}]
hw_f = physicsHW(hw_i);
hf_f → [{'K'} {}
{'v'} {}
{'m'} {[1.728]}]
This is my code right now:
function [E] = physicsHW(vars)
a = [];
%K = (0.5)(m)(v*v)
for i = 1:length(vars)
rows = vars(i,:)
for j = 1:length(rows)
if ischar(rows{j})==1
v = vars(i,j)
a = [a , v];
vars(i,j) = [] %error here: null assignment can have only one non-colon idx
end
end
end
Sindar on 6 Mar 2020
You can't delete individual cells from a matrix, but you don't need to for this problem. Instead, build a new matrix of the correct size (Nx2) and fill it iteratively

BobH on 14 Mar 2020
function kmvsolve
hw_i = {'K',5,2; 50,4,'v'; 70,'m',9 };
hw_o = physicsHW( hw_i )
end
function out = physicsHW( indata )
out = cell(0); % empty cell array that we can add to
for cr = 1:size(indata,1) % for each row
syms K m v; % start fresh
% hard code column numbers
if( ischar( indata{cr,1} ) )
letter = indata{cr,1};
m = indata{cr,2};
v = indata{cr,3};
elseif( ischar( indata{cr,2} ) )
K = indata{cr,1};
letter = indata{cr,2};
v = indata{cr,3};
elseif( ischar( indata{cr,3} ) )
K = indata{cr,1};
m = indata{cr,2};
letter = indata{cr,3};
end
val = solve( K == .5*m*v^2 );
% Accumulate results in a cell array
% after converting symbolic to a numeric
out(end+1,:) = { letter, double( val(1) ) };
end
end