Is it possible to convert a cell array into individual variables on workspace?

조회 수: 28 (최근 30일)
I have a 4x2 cell array of names and their values. I am trying to save them as a separate variable on workspace so that i can use them in my code. Is it possible to convert them into individual arrays?
Example: My cell array is
>> y(:,1)={'force';'mass';'distance';'gravity';'Unit'};
>> y(:,2)={'10';'0.5';'5';'10','N'};
% Desired Output:

답변 (1개)

Are Mjaavatten
Are Mjaavatten 2021년 3월 9일
Dynamically creating variables in Matlab is not encouraged. See Stephen Cobeldick's tutorial entry.
A better idea is to create a struct:
for i = 1:size(y,1)
s.(y{i,1}) = y{i,2};
end
  댓글 수: 2
Stephen23
Stephen23 2021년 3월 9일
y = {'force';'mass';'distance';'gravity';'Unit'};
y(:,2) = {'10';'0.5';'5';'10';'N'};
either
S = cell2struct(y(:,2),y(:,1))
S = struct with fields:
force: '10' mass: '0.5' distance: '5' gravity: '10' Unit: 'N'
or
y = y.';
S = struct(y{:})
S = struct with fields:
force: '10' mass: '0.5' distance: '5' gravity: '10' Unit: 'N'
Steven Lord
Steven Lord 2021년 3월 9일
y = {'force';'mass';'distance';'gravity';'Unit'};
y(:,2) = {10;0.5;5;10;'N'};
T =cell2table(y(:, 2).', 'VariableNames', y(:, 1))
T = 1x5 table
force mass distance gravity Unit _____ ____ ________ _______ _____ 10 0.5 5 10 {'N'}
T.distance
ans = 5
T{1, 'gravity'}
ans = 10
You could also set the RowNames of the table so you can do things like:
T.Properties.RowNames = {'trial1'}
T = 1x5 table
force mass distance gravity Unit _____ ____ ________ _______ _____ trial1 10 0.5 5 10 {'N'}
T{'trial1', 'force'}
ans = 10

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Tables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by