How to plot from listbox

3 views (last 30 days)
Brian Rreid
Brian Rreid on 8 Apr 2018
Answered: Divyajyoti Nayak on 11 Oct 2024
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

Answers (1)

Divyajyoti Nayak
Divyajyoti Nayak on 11 Oct 2024
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

Categories

Find more on Migrate GUIDE Apps 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!