Load Data in Matlab GUI - matlab

I am developing a GUI where I want the input in text or excel format from user. When he will click on "Upload File" button from my GUI, the file browser will open and he will select the text file. Once he clicks open the file should be in workspace so my next code will take the value give results.
What I did is: Have this code under the push button
[filename,pathname] = uigetfile('*.txt')
loaddata = fullfile(pathname,filename)
data = load(loaddata)
A = data(:,1)
B = data(:,2)
C = data(:,3)
D = data(:,4)
handles.input1 = A;
handles.input2 = B;
handles.input3 = C;
handles.input4 = D;
Now when the Browser opens, I can select .txt file which is having 4 columns and 2000 rows of data. But when I go back to workspace, I can't see anything in workspace but all values from 2nd column in command window!

You can use setappdata and the associated getappdata to store application-defined data and retrieve it from elsewhere, for example from a GUI or the base workspace.
In your case, you could store A, B, C and D in the base workspace so they would be available from your other scripts. You can also store the handles structure if you want.
As an example, your code in the GUI could look like this:
[filename,pathname] = uigetfile('*.txt')
loaddata = fullfile(pathname,filename)
data = load(loaddata)
%// Store in the base workspace (i.e. the "0")
setappdata(0,'AllData',data);
Note that you could write anything you want as a name, as long as you retrieve the variable with the same name using getappdata. Here I used AllData but you could leave that as data just as well.
Therefore, in the other script you are running, use getappdata like so:
DataInScript = getappdata(0,'AllData');
A = AllData(:,1)
B = AllData(:,2)
C = AllData(:,3)
D = AllData(:,4)
So now, depending on whether you already assigned A, B, C and D you can access your data directly from AllData.

Related

How to automatically change variable names given a new input file name

I am importing data from a .mat file and then extracting certain signals from it and I call this data, data. data is a 1x1 struct with 1 field, FT_est_X, where X is the the particular run that I collected the samples from. Here is the code snippet of how I do that.
data = load('site_data_all_2.mat');
t = data.FT_est_2.time;
% estimated data
Fx = data.FT_est_2.signals(1).values;
Fy = data.FT_est_2.signals(2).values;
Fz = data.FT_est_2.signals(3).values;
Mx = data.FT_est_2.signals(4).values;
My = data.FT_est_2.signals(5).values;
Mz = data.FT_est_2.signals(6).values;
So, you can see that this data was collected from run 2. Now, let's say I want to load in a file named site_data_all_3.mat (run 3), what happens is that all the data below %estimated data changes its name--everything stays the same, except the 2 becomes a 3 (e.g. Fx would be Fx = data.FT_est_3.signals(1).values;. Currently, I have to manually enter in the 3 for each variable; can anyone tell me how I can only change the file name and it will automatically change the variable names for me? Essentially, I just want it to be Fx = data.name_of_struct_field.signals(1).values.
Thank you!
You could construct the string some programmatic way (maybe with an iteration variable), but here's the simple answer of defining the fieldname as a string and simply using it. At the next iteration, update the fieldname variable and repeat.
fieldname = 'FT_est_2';
Fx = data.(fieldname).signals(1).values;

Matlab: read multiple files

my matlab script read several wav files contained in a folder.
Each read signal is saved in cell "mat" and each signal is saved in array. For example,
I have 3 wav files, I read these files and these signals are saved in arrays "a,b and c".
I want apply another function that has as input each signal (a, b and c) and the name of corresponding
file.
dirMask = '\myfolder\*.wav';
fileRoot = fileparts(dirMask);
Files=dir(dirMask);
N = natsortfiles({Files.name});
C = cell(size(N));
D = cell(size(N));
for k = 1:numel(N)
str =fullfile(fileRoot, Files(k).name);
[C{k},D{k}] = audioread(str);
mat = [C(:)];
fs = [D(:)];
a=mat{1};
b=mat{2};
c=mat{3};
myfunction(a,Files(1).name);
myfunction(b,Files(2).name);
myfunction(c,Files(3).name);
end
My script doesn't work because myfunction considers only the last Wav file contained in the folder, although
arrays a, b and c cointain the three different signal.
If I read only one wav file, the script works well. What's wrong in the for loop?
Like Cris noticed, you have some issues with how you structured your for loop. You are trying to use 'b', and 'c' before they are even given any data (in the second and third times through the loop). Assuming that you have a reason for structuring your program the way you do (I would rewrite the loop so that you do not use 'a','b', or 'c'. And just send 'myfunction' the appropriate index of 'mat') The following should work:
dirMask = '\myfolder\*.wav';
fileRoot = fileparts(dirMask);
Files=dir(dirMask);
N = natsortfiles({Files.name});
C = cell(size(N));
D = cell(size(N));
a = {};
b = {};
c = {};
for k = 1:numel(N)
str =fullfile(fileRoot, Files(k).name);
[C{k},D{k}] = audioread(str);
mat = [C(:)];
fs = [D(:)];
a=mat{1};
b=mat{2};
c=mat{3};
end
myfunction(a,Files(1).name);
myfunction(b,Files(2).name);
myfunction(c,Files(3).name);
EDIT
I wanted to take a moment to clarify what I meant by saying that I would not use the a, b, or c variables. Please note that I could be missing something in what you were asking so I might be explaining things you already know.
In a certain scenarios like this it is possible to articulate exactly how many variables you will be using. In your case, you know that you have exactly 3 audio files that you are going to process. So, variables a, b, and c can come out. Great, but what if you have to throw another audio file in? Now you need to go back in and add a 'd' variable and another call to 'myfunction'. There is a better way, that not only reduces complexity but also extends functionality to the program. See the following code:
%same as your code
dirMask = '\myfolder\*.wav';
fileRoot = fileparts(dirMask);
Files = dir(dirMask);
%slight variable name change, k->idx, slightly more meaningful.
%also removed N, simplifying things a little.
for idx = 1:numel(Files)
%meaningful variable name change str -> filepath.
filepath = fullfile(fileRoot, Files(idx).name);
%It was unclear if you were actually using the Fs component returned
%from the 'audioread' call. I wanted to make sure that we kept access
%to that data. Note that we have removed 'mat' and 'fs'. We can hold
%all of that data inside one variable, 'audio', which simplifies the
%program.
[audio{idx}.('data'), audio{idx}.('rate')] = audioread(filepath);
%this function call sends exactly the same data that your version did
%but note that we have to unpack it a little by adding the .('data').
myfunction(audio{idx}.('data'), Files(idx).name);
end

How to use file name to sort and count files stored in a .mat file?

dbhole.mat file contains files name like: d1h1,d1h2,d1h3,d1h4,d2h1,d2h2,d3h1,d3h2,d3h4,d3h5,d3h6.
I want to count the number of files having a name that starts with d1 then d2 ,d3 and so on in a loop.
If you mean that you want to get a list of the variables in a *.mat file that start with d1, d2, etc. You could use who and matfile to get a list of all variables. who accepts a regular expression which you can create specific to the variables you want to see.
matobj = matfile('filename.mat');
d1vars = who(matobj, '-regexp', '^d1h');
nD1 = numel(d1vars);
Or more generally in a loop
for k = 1:3
vars{k} = who(matobj, '-regexp', ['^d', num2str(k), 'h']);
% And get the number
nVars(k) = numel(vars{k});
end
If you have an older version of MATLAB, you can load the file into a struct and then check the fields of that struct for the pattern that you'd like.
data = load('filename.mat');
variables = fieldnames(data);
isd1 = variables(~cellfun(#isempty, regexp(variables, '^d1h')));
nD1 = numel(isd1);

Do the same for every part in listdlg (MATLAB)

I am writing a program and I am using listdlg. I want for each selection of the list to do the same thing BUT it will save them in different part(so that every option will have it's own - let's say- sub folder with its text files and they can be accessed for another function.
So this is my listdlg
global fileCount
F = listdlg('PromptString','Different types', 'SelectionMode',...
'single', 'ListString',{E}, 'Name','Select a type','ListSize',[230 130]);
where {E} is user's input, which might be 3 rows or 6 rows, how many he likes.
So I want if he uses the first row to ask for input and then save it for the first type
if F == 1
[file,path] = uigetfile ('*.txt','Select your text files',...
'MultiSelect','on');
file = cellstr(file);
for k = 1:length(file)
fileCount = length (file);
z = importdata(fullfile(path, file{k}));
end
end
the same will be done for the following types, meaning if he chooses the 2nd then the files will be saved for the 2nd file, but the files of the first type will not be overwrote. So he now has let's say Orange-10files; Pink-2files and Yellow-4files.
Is there a way I can do that? except using if and elseif for every of his choice?
I hope I was clear enough!
Thanks!
Assign E as a cell array rather than inserting it as a cell array in the listdlg call. I'm not entirely clear on your end goal, but this will take the user's selection of E's elements, open whatever files the user selects, and return the path and file name of those files with the added "color" folder:
E = {'Orange','Pink','Yellow'};
F = listdlg('PromptString','Different types', 'SelectionMode',...
'single', 'ListString',E, 'Name','Select a type','ListSize',[230 130]);
[files,path] = uigetfile ('*.txt','Select your text files',...
'MultiSelect','on');
files = cellfun(#(x) fullfile(path,E{F},x),files,'UniformOutput',false);

How to export data from Matlab to excel for a loop?

I have a code for "for loop"
for i=1:4
statement...
y=sim(net, I);
end
now i need to export the value of y to excel sheet. for that i used..
xlswrite('output_data.xls', y, 'output_data', 'A1')
but my problem is that the ID of excel i.e. "A1" should change according to each iteration... in my case for iteration 1-> A1, iteration-> A2 and so on..
anybody please help me out ..
thanks in advance. for any assistance.. or suggestion..
You can store sim outputs in a vector (y(ii)) and save in the sheet with a single write. This is also more efficient since you perform a single bulk-write instead of many small writes.
Specify the first cell and y will be written starting from there.
last = someNumber;
for i=1:last statement... y(i)=sim(net, I); end
xlswrite('output_data.xls', y', 'output_data', 'A1');
If you prefer specify the range write ['A1:A',num2str(last)] instead of A1.
If you really want to write within the loop try:
for ii=1:last
...
y=sim(net, I);
xlswrite('output_data.xls', y, 'output_data', sprintf('A%d',ii));
end
You can also do for yourself what xlswrite does internally, which is interact using COM. I prefer to do this when I have a frequently used excel template or data file, because it allows for more control (albeit with more lines of code).
Excel = actxserver('Excel.Application');
Workbook = Excel.Workbooks.Open('myExcelFile.xlsx');
MySheet = Excel.ActiveWorkBook.Sheets.Item(1);
set( get(MySheet,'Range','A1:A10'), 'Value', yourValues);
...
invoke(Workbook, 'Save');
invoke(Excel, 'Quit');
delete(Excel);
This would allow you to save new data to new ranges without re-opening excel each time.
Even better would be to define an oncleanup function (as does xlswrite) to prevent lost file locks (especially when you're doing things like exiting out of debug mode):
...
myWorkbook = Excel.Workbooks.Open(filename,0,true);
cleanUp = onCleanup(#()xlsCleanup(Excel, filename));
function xlsCleanup(Excel,filepath)
try
Excel.DisplayAlerts = 0; %// Turn off dialog boxes
[~,n,e] = fileparts(filepath); %// Excel API expects just the filename
fileName = [n,e];
Excel.Workbooks.Item(fileName).Close(false);
end
Excel.Quit;
end
You can put xlswrite after for loop.You just want to do is save you result in a matrix.This function can write a matrix.
also,you can use [] to combine string to change the range.
>> for i=1:4
Range=['A' num2str(i)]
end
Range =
A1
Range =
A2
Range =
A3
Range =
A4
But,this is a bad way.You should open and write Excel file every time.