Problem Loading Structures
4 views (last 30 days)
Show older comments
I need to display the structure name and title for the user to select the proper structures to open.
Here's an example of my code... Right now my program errors. I have tried several different ways. I have never used structures before. I have read the help docs but still don't understand...
[FileNameSpk,PathNameSpk] = uigetfile('*.*','Please Select File');
load([PathNameSpk FileNameSpk]); %Loads Structs
sname=load([PathNameSpk FileNameSpk]); %Loads Names of Structs
names=fieldnames(sname); %Finds Name of Struct
[fnum null]=size(names); %Fnum = number of Structs found
for i=1:fnum;
title(i,1)=getfield(names(i,1), 'title'); %Find Structure Title
end
for i=1:fnum;
info(i,1)=strcat(names(i,1), 'contains', title(i,1)); %'Struct contains title'
end
for i=1:fnum;
disp(info(i,1)) %Display file info for user
end
user1=input('Enter Channel number: '); %User selects Struct to Open
I use load([PathNameSpk FileNameSpk]) and add structures to the Workspace. title=getfield(names, 'title') gets the 'title' for the structures but I have to manually enter the structure's name. Is there a way for MATLAB to automatically extract the title of the structures without user input? Thanks for your help.
0 Comments
Accepted Answer
Jan
on 17 Aug 2011
Do not overwrite the built-in function "title" by a dynamically loaded variable. It is much faster, cleaner and more secure to catch the output of LOAD to a variable.
While "load([PathNameSpk FileNameSpk])" writes the variables stored in the MAT file directly tio the current workspace, "sname=load([PathNameSpk FileNameSpk])" writes the variables as fields to the struct sname. Then "sname.title" contains the variable "title" from the MAT file without hiding the function "title()".
It seems like your MAT-file contains structures only, which all have a field called 'title'. Then you can get them all by:
sname = load(fullfile(PathNameSpk, FileNameSpk));
data = struct2cell(sname);
data_title = cell(size(data));
for i = 1:numel(data)
data_title{i} = data{i}.title;
end
0 Comments
More Answers (1)
Image Analyst
on 17 Aug 2011
A structure doesn't have title(s). It has a name, and "members" (also known as "fields"), which also have names. The name of your structure is "sname" because that is what you sent the results of load() into. "sname" will have members, the names of which can be gotten by using the fieldnames() function, as you seem to already know. The fieldnames() function operates "automatically" without any user input.
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!