Creating a Cell Array but I've Got The Size Wrong and Its Missing Certain Elements

조회 수: 6 (최근 30일)
This section of code is meant to take an even number of input arguments and return them as a cell array with two columns, one for the name and one for the value. With the test input I've been given it is only returning the the third and forth input arguments as a 1x1 cell array where as I'm looking for a 2x2 cell array. Is the issue with the ii indexing? Can I not do it like I've written here?
db = name_value_pairs('name','John Smith','age',32)
function [db]=name_value_pairs(varargin)
for ii = 1:2:(length(varargin)-1)
for i = 1:(length(varargin)/2)
x(i,1) = varargin(ii);
end
end
for ii = 2:2:length(varargin)
for i = 1:(length(varargin)/2)
x(i,2) = varargin(ii);
end
end
db = {x};
end
db =
1×1 cell array
{2×2 cell}
Thank you for any help or advice!

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 9월 3일
The logic in your code seems to over-kill for this task. db = {x} statement make the return value a 1x1 array. If you change it to db = x you will get a 2x2 array.
You can use reshape() to write a one-liner
function [db]=name_value_pairs(varargin)
db = reshape(varargin, 2, []).';
end
  댓글 수: 10
Marcin Laszkiewicz
Marcin Laszkiewicz 2020년 9월 4일
편집: Marcin Laszkiewicz 2020년 9월 4일
Thank you Stephen and Ameer. Ameer, shouldn't it be:
if all(cellfun(@ischar, db(:,1)))
db = db;
else
db = {};
end
Or something similar? The way you have it written if @ischar is true then db is set as an empty array, right?
EDIT: Ok, finally got it!
function [db]=name_value_pairs(varargin)
if nargin < 2
db ={};
elseif rem(nargin, 2) ~= 0
db ={};
else
x = reshape(varargin, 2, []);
z = x';
if all(cellfun(@ischar, z(:,1)))
db = z;
else
db = {};
end
end
end
Thank you both so much, especially you Ameer. I appreciate the help and your endless patience.
Ameer Hamza
Ameer Hamza 2020년 9월 4일
Yes, you are correct. The condition should be reversed. The following is also equivalent.
function [db]=name_value_pairs(varargin)
if rem(nargin, 2) ~= 0 % I thought this would check for even # of inputs
db ={};
else
db = reshape(varargin, 2, []);
if ~all(cellfun(@ischar, db(:,1)))
db = {};
end
end
end

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

추가 답변 (0개)

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by