How to plot from listbox

3 次查看(过去 30 天)
Brian Rreid
Brian Rreid 2018-4-8
I need help with plotting data from a listbox. the program populates the list box from a folder containing multiple .CSV files, each file containing data. The file is then clicked on and plots a graph with the data. I cannot figure out how to plot the data. My instinct is to create a variable with the name of the file when clicked and then use csvread to extract the data and plot. What I can't figure out is how to set a variable to the clicked file in the listbox.
function homework8
f=figure;
x=linspace(0,6,10020);
a=axes('Position',[0.1300 0.1317 0.4593 0.7731])
listbox=uicontrol('style','list','position',....
[346.3333 54.3333 135.0000 283.3334],'Callback',@plot);
btn=uicontrol('parent',f,'style','pushbutton','position',...
[344.6667 349.6667 135.6667 30.3333],...
'String','Select Folder','Callback',@openfolder);
%%Callbacks
function openfolder(~,~)
folder = uigetdir();% returns the path for the directory
files = dir(folder); % sets the directory to chosen folder
listbox.String={files(:).name}; % puts files into listbox
end
%%plot data
%data=% my file name I click in listbox
y=csvread('data',18,2) %take data from file
plot(x,y)
end

回答(1 个)

Divyajyoti Nayak
Divyajyoti Nayak 2024-10-11
Hi Brian,
To plot data from the file selected in the list box, the name of the file needs to be extracted from the cell array in listbox.String. This can be done by using the listbox.Value property to index into the cell array.
Here’s some code to help:
f=figure;
x=linspace(0,6,10020);
a=axes('Position',[0.1300 0.1317 0.4593 0.7731]);
listbox=uicontrol('style','list','position',....
[346.3333 54.3333 135.0000 283.3334]);
listbox.Callback = {@Plot, listbox, a};
btn=uicontrol('parent',f,'style','pushbutton','position',...
[344.6667 349.6667 135.6667 30.3333],...
'String','Select Folder','Callback',{@openfolder,listbox});
%%Callbacks
function openfolder(~,~, lb)
folder = uigetdir();% returns the path for the directory
files = dir(folder); % sets the directory to chosen folder
lb.String ={files(:).name}; % puts files into listbox
end
function Plot(~,~,lb,ax)
fileName = lb.String{lb.Value}; %Getting file name from listbox.String
data = table2array(readtable(fileName)); %take data from file
plot(ax,data(:,1),data(:,2));
end

类别

Help CenterFile Exchange 中查找有关 Migrate GUIDE Apps 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by