how to rename fields in struc and adding new field name

조회 수: 6 (최근 30일)
TESFALEM ALDADA
TESFALEM ALDADA 2020년 12월 17일
댓글: TESFALEM ALDADA 2020년 12월 21일
Hello everyone
I have a stuct to work wit and i wonted to rename the field name (XX) by 'Area (km2)' and also i wanted to add new filed column between YY and ZZ as shown below.
wish you best

채택된 답변

Walter Roberson
Walter Roberson 2020년 12월 17일
struct fieldnames must be valid MATLAB identifiers, so spaces and brackets are not permitted.
The characters are permitted in the names of Variables in table() objects.
To add a new field at a particular location, the easiest way is to add the new field and then to use orderfields() to change the order.
  댓글 수: 3
Walter Roberson
Walter Roberson 2020년 12월 21일
foo = struct('a', 1, 'b', 2, 'd', 4);
foo.c = 3
foo = struct with fields:
a: 1 b: 2 d: 4 c: 3
%new field has been added but it is out of place
newfoo = orderfields(foo, {'d', 'c', 'b', 'a'})
newfoo = struct with fields:
d: 4 c: 3 b: 2 a: 1
%and now it is in very specific place
TESFALEM ALDADA
TESFALEM ALDADA 2020년 12월 21일
Okey it works fine thank you so much!!

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

추가 답변 (1개)

Jan
Jan 2020년 12월 21일
Adding a field at the end is trivial:
porositiy.newField = [];
Adding a field at a specific location is a bad idea, because the order of fields is not really fixed. But it works:
function S = AddFieldAfter(S, AfterField, NewField, NewData)
SField = fieldnames(S);
SData = struct2cell(S);
nS = numel(S);
sizeS = size(S);
index = find(strcmp(SField, AfterField));
if ~isempty(index)
SField = cat(1, SField(1:index), {NewField}, SField(index + 1:end));
if ~isequal(size(NewData), sizeS)
NewDataC = cell([1, nS]);
NewDataC(:) = {NewData};
end
SData = cat(1, SData(1:index, 1:nS), NewDataC, SData(index + 1:end, 1:nS));
S = reshape(cell2struct(SData, SField), sizeS);
else % Field not found, append at the end:
S.(NewField) = NewData;
end
end

카테고리

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