Saving a Structured Array (containing plot parameters) to a mat file

조회 수: 4 (최근 30일)
Jason
Jason 2024년 6월 24일
댓글: Jason 2024년 6월 24일
Hi, Im trying to save plot data by using a structured arra
ax=app.UIAxes;
ax.Children;
h1 = findall(ax, 'type', 'line'); % Line objects
nlines=numel(h1);
Assign the desired plot parameters to a struct "S"
for i=1:nlines
thisLine=h1(i);
S(i).Xdata=thisLine.XData; S(i).Ydata=thisLine.YData;
S(i).Colour=thisLine.Color;
S(i).LineStyle=thisLine.LineStyle;
S(i).LineWidth=thisLine.LineWidth;
S(i).DName=thisLine.DisplayName;
end
Save to a .MAT file
try
[file,folder]=uiputfile({'*.mat','Matlab Files'},'Save Data',app.startfolder);
catch
[file,folder]=uiputfile({'*.mat','Matlab Files'},'Save Data','C:\');
end
app.startfolder=folder;
savepath=fullfile(folder,file);
save(savepath,"-struct",'S')
But I keep getting this error:
Error using save
The argument to -STRUCT must be the name of a scalar structure variable.
I have checked the class of S and the fieldnames contained within it:
fields = fieldnames(S)
class(S)
fields =
6×1 cell array
{'Xdata' }
{'Ydata' }
{'Colour' }
{'LineStyle'}
{'LineWidth'}
{'DName' }
ans =
'struct'
Thanks for any help

채택된 답변

Stephen23
Stephen23 2024년 6월 24일
편집: Stephen23 2024년 6월 24일
Explanation: your structure is not scalar: it has nlines elements. The -struct option only works with scalar structures.
Error using save
The argument to -STRUCT must be the name of a scalar structure variable.
% ^^^^^^
Solutions:
  • either get rid of the -struct option, or
  • create a scalar structure (by making the fields arrays, not the structure).
Tip: always LOAD into an output variable!
  댓글 수: 3
Steven Lord
Steven Lord 2024년 6월 24일
Since several of the properties you're trying to store in the struct are non-scalar, it won't work as you wrote it. But you could have the fields of the scalar struct contain cell arrays, where each cell in the array can have data of different sizes depending on the properties of the specific line you're trying to store inside it.
h = plot(1:10, 1:10, 'r-', 1:7, 10:-1:4, 'k:');
for k = 1:numel(h)
S.XData{k} = h(k).XData;
S.YData{k} = h(k).YData;
end
disp(S)
XData: {[1 2 3 4 5 6 7 8 9 10] [1 2 3 4 5 6 7]} YData: {[1 2 3 4 5 6 7 8 9 10] [10 9 8 7 6 5 4]}
isscalar(S) % yes
ans = logical
1
isstruct(S) % also yes
ans = logical
1
cd(tempdir)
save('mydata.mat', '-struct', 'S')
whos -file mydata.mat
Name Size Bytes Class Attributes XData 1x2 344 cell YData 1x2 344 cell
P = load('mydata.mat')
P = struct with fields:
XData: {[1 2 3 4 5 6 7 8 9 10] [1 2 3 4 5 6 7]} YData: {[1 2 3 4 5 6 7 8 9 10] [10 9 8 7 6 5 4]}
isequal(P, S)
ans = logical
1
Jason
Jason 2024년 6월 24일
Thats fantastic, thankyou!

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

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by