How do I delete cell elements from a cell array?

7 vues (au cours des 30 derniers jours)
Shahriyar Karim
Shahriyar Karim le 6 Mar 2020
Réponse apportée : BobH le 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'} {[5]} {[2]}
{[50]} {[4]} {'v'}
{[70]} {'m'} {[9]}]
hw_f = physicsHW(hw_i);
hf_f → [{'K'} {[10]}
{'v'} {[5]}
{'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
  1 commentaire
Sindar
Sindar le 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

Connectez-vous pour commenter.

Réponses (1)

BobH
BobH le 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

Catégories

En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by