How do I delete cell elements from a cell array?

4 ビュー (過去 30 日間)
Shahriyar Karim
Shahriyar Karim 2020 年 3 月 6 日
回答済み: BobH 2020 年 3 月 14 日
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 件のコメント
Sindar
Sindar 2020 年 3 月 6 日
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

サインインしてコメントする。

回答 (1 件)

BobH
BobH 2020 年 3 月 14 日
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

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by