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 CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by