structure containing empty string arrays

조회 수: 3 (최근 30일)
Tom Wright
Tom Wright 2013년 2월 19일
Hi, I'm using a structure to hold some text data. The fields of the structure are initialised as cells. However it seems that if the field is left empty then the value is converted to a double meaning I can't consistently index that value. Do I need to specifically test each value or is there a better way? Thanks
x=struct('a',{},'b',{});
x(1).a={'abc' 'bbc'};
x(1).b={'cbc'};
x(2).a={'dbc'};
for iloc=1:2
sprintf('%s,%s\n',...
x(iloc).a{:},...
x(iloc).b{:})
end

답변 (2개)

Azzi Abdelmalek
Azzi Abdelmalek 2013년 2월 19일
편집: Azzi Abdelmalek 2013년 2월 19일
You can use
x=struct('a',{''},'b',{''});
Edit
n=10;
v=arrayfun(@(x) {''},1:n,'un',0)
a=struct('a',v,'b',v)
  댓글 수: 5
Tom Wright
Tom Wright 2013년 2월 19일
Hmm, just spotted a typo in my original question, now corrected. I can't preallocate the structure completely since I don't know how many values I'm going to find. The solution
x=struct('a',{'','',''},'b',{'','',''});
also doesn't work as required
type(x(2).b) = char
Azzi Abdelmalek
Azzi Abdelmalek 2013년 2월 19일
편집: Azzi Abdelmalek 2013년 2월 19일
Ok, use this, it should work
n=10;
v=arrayfun(@(x) {''},1:n,'un',0)
a=struct('a',v,'b',v)

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


Sean de Wolski
Sean de Wolski 2013년 2월 19일
편집: Sean de Wolski 2013년 2월 19일
You should be able to use repmat() to create a cell array of empty strings:
C = repmat({''},10,10)
And then feed this into the struct() constructor.
  댓글 수: 1
Sean de Wolski
Sean de Wolski 2013년 2월 19일
@Tom, works fine for me:
C = repmat({''},10,10)
S = struct('C',C)
S(10,1).C = 'pi'

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

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by