How can Ido the same operations with multiples files using for-loop

I developed the a code for one specific file (spike1.mat). Now I want to run this code for n files (spike1.mat, spike2.mat, spike3.mat, so on). Nested for-loop seems to be the best function, but I don't know how the (nested) for-loop makes the operation for the first file, for the second file, and so on. In other words,I don't know how I can integrate my operations into the for-loop because I don't know how to name the files.
This is my entire code:
clear;clc;
function = spike_analysis
load 'spike1.mat';
%Plot the spike with a corrected baseline
A=spike1(:,1);
B=spike1(:,2);
B1=B-(min(B)); %Baseline is 0 if the minimum value is different than 0.
figure(1)
plot(A,B1)
ylabel('Intensity (pA)')
xlabel('Time(s)')
title('1st spike')
format longG
% The parameters for the entire spike
% Charge of the entire spike
%The inmediate integration of the vector Intensity during the time is the
%charge (Q), i.e. the amount of molecules released per vesicle.
Q_spike=trapz(A,B1)*10^3
% The Increment of time of the Half Width of the spike
%Find the Time (second) when Intensity is maximum
%[a b]=max(Fst_spike(:,2));
%Time_maxI=Fst_spike(b,1)
% The Increment of time of Half Width.
%Find the half max value.
halfMax = max(B1) / 2;
index1_HW = find(B1 >= halfMax, 1, 'first'); %Gives the number of the row where data first drops below half the max.
index2_HW = find(B1 >= halfMax, 1, 'last'); %Gives the number of the row where data last rises above half the max.
Ti_HW=A(index1_HW,1)
Tf_HW=A(index2_HW,1)
AT_HW=(Tf_HW-Ti_HW)*10^6
%The Rise Time (the time span between the 50% and the 90% of the
%maxIntensty).
% Find the 90% of the maxIntensity.
RT_90 = max(B1) * 0.90;
index1_RT = find(B1 >= halfMax, 1, 'first'); %Gives the number of the row where data first rises above half the max.
index2_RT = find(B1 >= RT_90, 1, 'first'); %Gives the number of the row where data first drops below 90% of the max.
Ti_RT=A(index1_RT,1)
Tf_RT=A(index2_RT,1)
AT_RT=(Tf_RT-Ti_RT)*10^6
% The paramenters of the foot signal
load 'footsignal_spike1.mat'
A_f=footsignal_spike1(:,1);
B_f=footsignal_spike1(:,2);
figure (2)
plot(A_f,B_f)
ylabel('Intensity (pA)')
xlabel('Time(s)')
title('1st foot signal')
% Charge of the foot signal
Q_footsignal=trapz(A_f,B_f)*10^3
% Max amplitude of the foot signal
MaxI_f=max(B_f)
% Foot signal duration
Ti_f=min(A_f)
Tf_f=max(A_f)
AT_f=(Tf_f-Ti_f)*10^6
%Save the parameters and the entire spike figure
Table_parameters_spike1=table(MaxI_f,Q_footsignal,Ti_f,Tf_f,AT_f,AT_HW,AT_RT,halfMax,index1_HW,index2_HW,index1_RT,index2_RT,Q_spike,RT_90)
writetable (Table_parameters_spike1,'Parameters 1 spike.xlsx')
savefig(figure(1),'1st spike.fig')
savefig(figure(2),'1st footsignal.fig')
For example, how can I do the first step, the plot? How can I plot the first file?
Thanks!

1 Comment

"I tried this code ...How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F but I cannot make it to work."
Creating variables (which is a singularly bad way to write code) is completely unrelated to processing multiple files in a loop. So that link does not help you at all.
You should start learning about how to process multiple files by reading this:
and following Adam Danz's advice.

Sign in to comment.

 Accepted Answer

A function is designed to have inputs and outputs though neither are required but in general the idea is:
---> [ do stuff] -->
For example, instead of defining what file should be loaded within the function, you could pass the file name in as an input like this.
function = spike_analysis(file1, file2) %make better variable names
load(file1) % though, see bullet points below
load(file2)
. . .
end
Now you can merely call your function like this
spike_analysis('spike1.mat', 'footsignal_spike1.mat')
If you'd like to loop through many files, you could write a wrapper function that merely selects the files and calls your main spike_analysis() function.
function = spike_analysis_wrapper()
filepairs = {
'spike1.mat', 'footsignal_spike1.mat';
'spike2.mat', 'footsignal_spike2.mat';
'spike3.mat', 'footsignal_spike3.mat';
'spike4.mat', 'footsignal_spike4.mat'};
% Loop through each row of filepairs
for i = 1:size(filepairs,1))
spike_analysis(filepairs{i,1},filepairs{i,2});
end
Here is a list of other advice pertaining to the code in your question
  • Starting a function with "clear;clc;" is unnecessary. A function has its own workspace which starts out cleared.
  • A general rule is that a function should do 1 thing. Often times it's cleaner to separate the analysis from the plotting (but not always).
  • The function name should be descriptive; action verbs are good. plot_spike_analysis()
  • Using load() without outputs and without specifying variables in the inputs is sloppy and is the least controlled way to load variables.
  • Full paths are always better than mere filenames. If you have more than 1 file named "spike1.mat" anywhere on your matlab path, you have less control over which one is being loaded.
  • Does the save commands at the end of your function overwrite the same file each time? Filenames should always be related to the unique inputs or contain a datetime stamp unless you intend for files to be overwritten. Alternatively, use full paths and save the files in different locations.
  • Instead of writing the table and saving the figures within the plotting function, that could be done from the wrapper function as well (demo below) by using function outputs.
function = [Table_parameters_spike1, fig1, fig2] = spike_analysis(file1, file2) %make better variable names
load(file1) % though, see bullet points below
load(file2)
. . .
end
function = spike_analysis_wrapper()
filepairs = {
'spike1.mat', 'footsignal_spike1.mat';
'spike2.mat', 'footsignal_spike2.mat';
'spike3.mat', 'footsignal_spike3.mat';
'spike4.mat', 'footsignal_spike4.mat'};
% Loop through each row of filepairs
for i = 1:size(filepairs,1))
[Table_parameters_spike1, fig1, fig2] = spike_analysis(filepairs{i,1},filepairs{i,2});
writetable (Table_parameters_spike1,'Parameters 1 spike.xlsx')
savefig(fig1,'1st spike.fig')
savefig(fig2,'1st footsignal.fig')
end

16 Comments

Hi Adam,
Thanks for your answer.
Unfortunately, my knowlage for loops in matlab is very poor. I understood nothing from your code. Some of the advices were easy to understand.
I copied and pasted your code like this.
function spike_analysis_wrapper()
filepairs = {
'spike1.mat', 'footsignal_spike1.mat';
'spike2.mat', 'footsignal_spike2.mat';
'spike3.mat', 'footsignal_spike3.mat';
'spike4.mat', 'footsignal_spike4.mat'};
% Loop through each row of filepairs
for i = 1:size(filepairs,1)
[Table_parameters_spike1, fig1, fig2] = spike_analysis(filepairs{i,1},filepairs{i,2});
writetable (Table_parameters_spike1,'Parameters 1 spike.xlsx')
savefig(fig1,'1st spike.fig')
savefig(fig2,'1st footsignal.fig')
end
%Plot the spike with a corrected baseline
A=spike1(:,1);
B=spike1(:,2);
B1=B-(min(B)); %Baseline is 0 if the minimum value is different than 0.
figure(1)
plot(A,B1)
ylabel('Intensity (pA)')
xlabel('Time(s)')
title('1st spike')
format longG
% The parameters for the entire spike
% Charge of the entire spike
%The inmediate integration of the vector Intensity during the time is the
%charge (Q), i.e. the amount of molecules released per vesicle.
Q_spike=trapz(A,B1)*10^3
% The Increment of time of the Half Width of the spike
%Find the Time (second) when Intensity is maximum
%[a b]=max(Fst_spike(:,2));
%Time_maxI=Fst_spike(b,1)
% The Increment of time of Half Width.
%Find the half max value.
halfMax = max(B1) / 2;
index1_HW = find(B1 >= halfMax, 1, 'first'); %Gives the number of the row where data first drops below half the max.
index2_HW = find(B1 >= halfMax, 1, 'last'); %Gives the number of the row where data last rises above half the max.
Ti_HW=A(index1_HW,1)
Tf_HW=A(index2_HW,1)
AT_HW=(Tf_HW-Ti_HW)*10^6
%The Rise Time (the time span between the 50% and the 90% of the
%maxIntensty).
% Find the 90% of the maxIntensity.
RT_90 = max(B1) * 0.90;
index1_RT = find(B1 >= halfMax, 1, 'first'); %Gives the number of the row where data first rises above half the max.
index2_RT = find(B1 >= RT_90, 1, 'first'); %Gives the number of the row where data first drops below 90% of the max.
Ti_RT=A(index1_RT,1)
Tf_RT=A(index2_RT,1)
AT_RT=(Tf_RT-Ti_RT)*10^6
% The paramenters of the foot signal
load 'footsignal_spike1.mat'
A_f=footsignal_spike1(:,1);
B_f=footsignal_spike1(:,2);
figure (2)
plot(A_f,B_f)
ylabel('Intensity (pA)')
xlabel('Time(s)')
title('1st foot signal')
% Charge of the foot signal
Q_footsignal=trapz(A_f,B_f)*10^3
% Max amplitude of the foot signal
MaxI_f=max(B_f)
% Foot signal duration
Ti_f=min(A_f)
Tf_f=max(A_f)
AT_f=(Tf_f-Ti_f)*10^6
%Save the parameters and the entire spike figure
Table_parameters_spike1=table(MaxI_f,Q_footsignal,Ti_f,Tf_f,AT_f,AT_HW,AT_RT,halfMax,index1_HW,index2_HW,index1_RT,index2_RT,Q_spike,RT_90)
writetable (Table_parameters_spike1,'Parameters 1 spike.xlsx')
savefig(figure(1),'1st spike.fig')
savefig(figure(2),'1st footsignal.fig')
end
But I got this error:
Cannot find an exact (case-sensitive) match for 'spike_analysis'
The closest match is: Spike_analysis in
C:\Users\physiol\Desktop\Jose\Lab\Data\Matlab_files_spikes_analysis\Spike_analysis.m
Error in Spike_analysis (line 10)
[Table_parameters_spike1, fig1, fig2] = spike_analysis(filepairs{i,1},filepairs{i,2});
What am I doing wrong?
" my knowlage for loops in matlab is very poor"
Let's tackle that first. For-loops are a very basic, level-1 concept. There are some very basic, intuitive examples in the documentation here:
Here's an additional demo that should make sense.
x = 2;
for i = 1:10
y = x * i;
end
This "loop" will execute 10 times or 10 "iterations". On each iteration, the i value will change from 1 to 2 to 3.... to 10. So on the first iteration y will equal x*1. On the 2nd iteration y will equal x*2 etc.
In my answer, there are two separate functions. The first is your spike analysis / plotting function. The second is a "wrapper function" that calls your first function. Those two functions should not be within the same file.
Why don't you edit your comment above so that there are two, separate functions. You only need to run the wrapper function because it will call the other function. If you continue to have errors that you cannot solve, let's continue the discussion.
" Let's tackle that first. For-loops are a very basic, level-1 concept. There are some very basic, intuitive examples in the documentation here:
Here's an additional demo that should make sense.
x = 2;
for i = 1:10
y = x * i;
end "
The very basics of for-loop are simple.
In my case, I need something more complicated. I was looking to find some thread or video that explain how to do the same operation to a series of files (that is my case) and I found the nested for-loop one of the solutions. That is the reason I took this function.
Just note that the codes for explaining the basics of for-loop and the code you wrote are quite different. Yours is so much complicated for my level, but the level-1 concepts are very easy. I am trying to find the mid-point to follow you up :-)
"In my answer, there are two separate functions. The first is your spike analysis / plotting function. The second is a "wrapper function" that calls your first function. Those two functions should not be within the same file."
I separate the 3 functions and I run them in the following order.
1) This works (please note trial is the name of the function/script):
function trial = Spike_analysis_wrapper(spike1, spike2) %make better variable names
load('spike1.mat') % though, see bullet points below
load('spike2.mat')
end
2) Also this one:
function [Table_parameters_spike1, fig1, fig2] = spike_analysis_wrapper(spike1, spike2) %make better variable names
load('spike1.mat') % though, see bullet points below
load('spike2.mat')
end
3) But in this one, I got the same error.
function trial2 = spike_analysis_wrapper()
filepairs = {
'spike1.mat', 'footsignal_spike1.mat';
'spike2.mat', 'footsignal_spike2.mat';
'spike3.mat', 'footsignal_spike3.mat';
'spike4.mat', 'footsignal_spike4.mat'};
% Loop through each row of filepairs
for i = 1:size(filepairs,1)
[Table_parameters_spike1, fig1, fig2] = spike_analysis_wrapper(filepairs{i,1},filepairs{i,2});
writetable (Table_parameters_spike1,'Parameters 1 spike.xlsx')
savefig(fig1,'1st spike.fig')
savefig(fig2,'1st footsignal.fig')
end
>> trial2
Cannot find an exact (case-sensitive) match for 'spike_analysis_wrapper'
The closest match is: Spike_analysis_wrapper in
C:\Users\physiol\Desktop\Jose\Lab\Data\Matlab_files_spikes_analysis\Spike_analysis_wrapper.m
Error in trial2 (line 6)
[Table_parameters_spike1, fig1, fig2] = spike_analysis_wrapper(filepairs{i,1},filepairs{i,2});
I really appreciate your dedication on this thread. I keep looking for some advanced lesson in this topic.
The for-loop in my answer isn't too different from the ones in the simpler examples. Let me add some comments to explain.
for i = 1:size(filepairs,1))
% This just means that you will create a loop that starts
% at i=1 and ends at i=size(filepairs,1).
% size(filepairs,1) is just the number of rows in filepairs.
% So, you're looping through the number of rows. In the
% example there are 5 rows so it would be the same as
% for i = 1:5
spike_analysis(filepairs{i,1},filepairs{i,2});
% Here you're just choosing the i-th row of filepairs
% on each iteration. You're selecting what row of
% files to send to spike_analysis().
end
This block below is incorrect for the following reasons.
  • what are the inputs and what do they do within the function?
  • the function loads data and then does nothing with the data.
  • The output "trial" doesn't appear anywhere in the function.
function trial = Spike_analysis_wrapper(spike1, spike2) %make better variable names
load('spike1.mat') % though, see bullet points below
load('spike2.mat')
end
The 2nd function you shared looks like it's the same thing as the first function.
I have no idea what the intensions are of the 3rd function.
Correct way
You need 2 functions. The first function will be a slight modification of your existing function shared in your quesiton.
function = spike_analysis(file1,file2)
load(file1)
%Plot the spike with a corrected baseline
A=spike1(:,1);
. . . % skipping some code.....
% The paramenters of the foot signal
load(file2)
A_f=footsignal_spike1(:,1);
. . . % Skipping some code.....
And your second function saved to a different file (the wrapper function)
function = spike_analysis_wrapper()
filepairs = {
'spike1.mat', 'footsignal_spike1.mat';
'spike2.mat', 'footsignal_spike2.mat';
'spike3.mat', 'footsignal_spike3.mat';
'spike4.mat', 'footsignal_spike4.mat'};
% Loop through each row of filepairs
for i = 1:size(filepairs,1))
% Send the 2 files in row "i" into the analysis
spike_analysis(filepairs{i,1},filepairs{i,2});
end
Hi Adam,
We feel I am close to the end. Although both functions are working, there is a "small" issue: spike_analysis_wrapper runs twice the first filepair (spike1 and footsignal_spike1).
Here is the first function (spike_analysis) shortened to make it easier:
function spike_analysis (file1,file2)
load 'spike1.mat';
%Plot the spike with a corrected baseline
A=spike1(:,1);
B=spike1(:,2);
B1=B-(min(B)); %Baseline is 0 if the minimum value is diferent than 0.
figure(1)
plot(A,B1)
ylabel('Intensity (pA)')
xlabel('Time(s)')
title('1st spike')
% The paramenters of the foot signal
load 'footsignal_spike1.mat'
A_f=footsignal_spike1(:,1);
B_f=footsignal_spike1(:,2);
figure (2)
plot(A_f,B_f)
ylabel('Intensity (pA)')
xlabel('Time(s)')
title('1st foot signal')
%Save the parameters and the entire spike figure
Parameters_spike1=table(MaxI_f,Q_footsignal,Ti_f,Tf_f,AT_f,AT_HW,AT_RT,halfMax,index1_HW,index2_HW,index1_RT,index2_RT,Q_spike,RT_90)
writetable (Parameters_spike1,'Parameters spike1.xlsx')
savefig(figure(1),'1st spike.fig')
savefig(figure(2),'1st footsignal.fig')
end
Here the second function (spike_analysis_wrapper) that runs twice the first two files:
function spike_analysis_wrapper()
filepairs = {
'spike1.mat', 'footsignal_spike1.mat';
'spike2.mat', 'footsignal_spike2.mat';};
% Loop through each row of filepairs
for i = 1:size(filepairs,1)
% Send the 2 files in row "i" into the analysis
spike_analysis(filepairs{i,1},filepairs{i,2});
end
I think the problem lies on the first function. It is only load 'spike1.mat' and 'footsignal_spike1.mat' because these are the only two files loaded in this file. So, how can I write in the first function "take the files the function spike_analysis_wrapper gives to you"? I bet this is the core of the problem.
Thanks in advance Adam!
Yes, you're getting closer, Jose. There's one major concept that I've tried to explain but it is still not understood. Let me try a different way. Please take a few minutes to understand this very small example below. If you don't understand this first section, please do not read any further and spend more time digesting this first part.
function c = add_two_numbers(a,b)
% The purpose of this function is to add two numbers, a and b,
% and return the answer, c.
c = a + b.
end
Now, let's call that function.
c = add_two_numbers(2,3);
% answer: c = 5;
c = add_two_numbers(5,1);
% answer: c = 6
c = add_two_numbers(-2,2);
% answer: c = 0
____________ Is the section above clear?_____________
Now let's look at your main function spike_analysis (file1,file2).
Notice that your inputs "file1" and "file2" are never used within your function. They are variables and they never appear anywhere within the function.
"file1" and "file2" are supposed to contain strings that specify which files will be loaded.
Here's another example function below. There are 2 inputs and each input specifies what files should be loaded into the function.
function load_two_files(file1, file)
load(file1) % Note that there are no quotes!
load(file2)
end
Now let's call that function with the line below. Note that nothing will happen other than those two files will be loaded into the function workspace and then the function will end.
load_two_file('spike1.mat','footsignal_spike1.mat')
So your function should appear like this:
function spike_analysis (file1,file2)
% load 'spike1.mat'; <-------------------------------- REMOVE THIS !!!
load(file1) % <------------------------------------------ADD THIS INSTEAD
%Plot the spike with a corrected baseline
A=spike1(:,1);
B=spike1(:,2);
B1=B-(min(B)); %Baseline is 0 if the minimum value is diferent than 0.
figure(1)
plot(A,B1)
ylabel('Intensity (pA)')
xlabel('Time(s)')
title('1st spike')
% The paramenters of the foot signal
% load 'footsignal_spike1.mat' <----------------------- REMOVE THIS !!!
load(file2) % <------------------------------------------ADD THIS INSTEAD
A_f=footsignal_spike1(:,1);
B_f=footsignal_spike1(:,2);
figure (2)
plot(A_f,B_f)
ylabel('Intensity (pA)')
xlabel('Time(s)')
title('1st foot signal')
%Save the parameters and the entire spike figure
Parameters_spike1=table(MaxI_f,Q_footsignal,Ti_f,Tf_f,AT_f,AT_HW,AT_RT,halfMax,index1_HW,index2_HW,index1_RT,index2_RT,Q_spike,RT_90)
writetable (Parameters_spike1,'Parameters spike1.xlsx')
savefig(figure(1),'1st spike.fig')
savefig(figure(2),'1st footsignal.fig')
end
In this function, a and b are mencioned later so they are not like file 1 and file 2.
"Notice that your inputs "file1" and "file2" are never used within your function. They are variables and they never appear anywhere within the function. "
function c = add_two_numbers(a,b)
% The purpose of this function is to add two numbers, a and b,
% and return the answer, c.
c = a + b.
end
So, I do not get the point of this code to understand the other function.
I tried to run this code you wrote several times and it is not working
function spike_analysis (file1,file2)
% load 'spike1.mat'; <-------------------------------- REMOVE THIS !!!
%Plot the spike with a corrected baseline
A=spike1(:,1);
B=spike1(:,2);
B1=B-(min(B)); %Baseline is 0 if the minimum value is diferent than 0.
figure(1)
plot(A,B1)
ylabel('Intensity (pA)')
xlabel('Time(s)')
title('1st spike')
% The paramenters of the foot signal
% load 'footsignal_spike1.mat' <----------------------- REMOVE THIS !!!
A_f=footsignal_spike1(:,1);
B_f=footsignal_spike1(:,2);
figure (2)
plot(A_f,B_f)
ylabel('Intensity (pA)')
xlabel('Time(s)')
title('1st foot signal')
%Save the parameters and the entire spike figure
Parameters_spike1=table(MaxI_f,Q_footsignal,Ti_f,Tf_f,AT_f,AT_HW,AT_RT,halfMax,index1_HW,index2_HW,index1_RT,index2_RT,Q_spike,RT_90)
writetable (Parameters_spike1,'Parameters spike1.xlsx')
savefig(figure(1),'1st spike.fig')
savefig(figure(2),'1st footsignal.fig')
end
However, I got an idea. SO the folllowing code is the one that picks up the files, picks up the function (do stuff) and makes the for-loop, right?
function Spike_analysis_wrapper()
filepairs = {
'spike1.mat', 'footsignal_spike1.mat';
'spike2.mat', 'footsignal_spike2.mat';};
% Loop through each row of filepairs
for i = 1:size(filepairs,1)
% Send the 2 files in row "i" into the analysis
Spike_analysis(filepairs{i,1},filepairs{i,2});
end
filepair variable picks the files and the for-loop picks the main function for the files.
Then, lets go to the main function:
function Spike_analysis(file1,file2)
%Plot the spike with a corrected baseline
A=spike1(:,1);
B=spike1(:,2);
B1=B-(min(B)); %Baseline is 0 if the minimum value is different than 0.
figure(1)
plot(A,B1)
ylabel('Intensity (pA)')
xlabel('Time(s)')
title('1st spike')
format longG
A_f=footsignal_spike1(:,1);
B_f=footsignal_spike1(:,2);
figure (2)
plot(A_f,B_f)
ylabel('Intensity (pA)')
xlabel('Time(s)')
title('1st foot signal')
end
What can I write instead of "spike1" and "footsignal_spike1" to make it run? I cannot write there neither file1 nor file2, right? I tried to include the variable filepairs there put it doesn't work. I did it because the Spike_analysis variable in the for-loop takes the filepairs to operate. But the function Spike_analysis has been defined to take everytime 'spike1.mat' and 'footsignal_spike1.mat' files. Also, If I put twice spike1 and footsignal_spike1 in the filepairs, it works! Because the Spike_analysis function only allows this file to be operated by the for-loop, isn't it?
Conclusion: I have to change this to make it run.
A=spike1(:,1);
B=spike1(:,2);
A_f=footsignal_spike1(:,1);
B_f=footsignal_spike1(:,2);
Am i right?
You're still not understanding how functions and function-inputs work.
When you run this line below
Spike_analysis('spike1.mat','footsignal_spike1.mat');
then the input variable "file1" BECOMES "spike1.mat" and the input variable "file2" BECOMES "footsignal_spike1.mat".
So if you want the load "spike1.mat" you just need to use load(file1).
"What can I write instead of "spike1" and "footsignal_spike1" to make it run? I cannot write there neither file1 nor file2, right? "
Wrong. file1 IS "spike1.mat" and file2 IS "footsignal_spike1.mat" (or whatever inputs were provided).
"I tried to run this code you wrote several times and it is not working"
I updated that section of code so your variables are loaded correctly. See the 2 comments "ADD THIS INSTEAD". Try it again and if it's not working explain why it's not working. If there as an error message provide the full copy-pasted msg.
This is the error I got from the code:
Undefined function or variable 'spike1'.
Error in spike_analysis (line 5)
A=spike1(:,1);
Error in spike_analysis_wrapper (line 8)
spike_analysis(filepairs{i,1},filepairs{i,2});
>>
The first files are loaded (spike1 and footsignal_spike1), but the rest of the files are not loaded into the loop.
For this reason, if I change the wrapper code it runs twice the spike1 and footsignal_spike1.
function spike_analysis_wrapper()
filepairs = {
'spike1.mat', 'footsignal_spike1.mat';
'spike1.mat', 'footsignal_spike1.mat'};
% Loop through each row of filepairs
for i = 1:size(filepairs,1)
% Send the 2 files in row "i" into the analysis
spike_analysis(filepairs{i,1},filepairs{i,2});
end
So this function only accepts spike1-related files. Never spike2.
"Wrong. file1 IS "spike1.mat" and file2 IS "footsignal_spike1.mat" (or whatever inputs were provided)."
This IS the PROBLEM. I do not want spike1 named differently. I want to pick spike1 AND spike2, spike3, spike4 and so on. The same with footsignal_spike1.
I think you do not understand my first question. How can I do the same operation (e.g. spike_analysis) with multiple files (e.g. file1, file2, file3, file4) in a for-loop (e.g. spike_analysis_wrapper)?
If you want to apply your analysis to [spike1 & footsignal_spike1] and then you want to apply your analysis to [spike2 & footsignal_spike2] and so on, then we're on the same page.
If you want to load all of the files at 1 time and combine the data into 1 big group and then apply your analysis to that 1 big group of data, that is not how I interpretted "I want to run this code for n files". Is that what you'd like to do?
Jose Rego Terol's "Answer" moved here:
"If you want to apply your analysis to [spike1 & footsignal_spike1] and then you want to apply your analysis to [spike2 & footsignal_spike2] and so on, then we're on the same page."
Yes, we are on the same page. The function spike_analysis_wrapper is not able to load the second set of files (spike2 & footsignal_spike2) after loading succesfully the first set of files (spike1 & footsignal_spike1). This is the problem.
Undefined function or variable 'spike1'.
Error in spike_analysis (line 5)
A=spike1(:,1);
Error in spike_analysis_wrapper (line 8)
spike_analysis(filepairs{i,1},filepairs{i,2});
Attach both of your functions as m-files so I can see what you're doing.
Hi Jose,
part 1
I checked out the files you attached in your answer. Please take some time to check out this helpful page in order to understand how functions and function-inputs work.
In your wrapper function, this line
Spike_analysis2(k)
is merely sending the value of k (an integer) into your spike_analysis function. For example, k equals 1 on the first iteration. The spike_analysis function receives the value of 1 but what is the function supposed to do with that? It needs a filename, not an integer. To fix that, the line should be
Spike_analysis2(fullFileName)
part 2
Then, in the spike_analysis function, this line
S = load(file1);
will load a data structure. The structure will contain a field for each variable saved in the file.
S =
struct with fields:
footsignal_spike1: [175×2 double]
S.footsignal_spike1 %this is your matrix (try it!)
part 3
I did not run the rest of your code. Now you know 1) how to set up the wrapper function so it can send in a file name in the form of a string and 2) how to load the data from the specified file. Now you can apply this knowledge to your code and set it up so it runs properly. This addresses your problem and I think you can handle the rest from here.
Hi Adam,
The problem was this guy Spike_analysis2(fullFileName)
Thanks a lot for you patience and your time spent!

Sign in to comment.

More Answers (1)

Hi Adam,
Thanks for your comment. Here I attached the functions as m-files and the files I want to load both to the for-loop and to the analysis function.
Now, when I run the wrapper I got this error:
>> Spike_analysis_wrapper2
Now reading footsignal_spike1.mat
Error using load
Must be a string scalar or character vector.
Error in Spike_analysis2 (line 18)
S = load(file1);
Error in Spike_analysis_wrapper2 (line 35)
Spike_analysis2(k)
It's strange because yesterday it worked, but using the filepairs.
Thanks again!

5 Comments

Hi Adam, it's me again :)
I am struggling with the table.
The table code only takes the first output of the function. I couldn't find how I can increase the number of inputs for the table.
Also, I have problems saving the table.
May you help me?
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', baseFileName)
%Call the function Spike_analysis
t=spike_analysis_file1(baseFileName)
end
table(t)
writetable(t,'Parameters spike.xlsx')
Now reading spike5.mat
t =
4.04856
ans =
table
t
_______
4.04856
Undefined function 'write' for input arguments of type 'double'.
Error in writetable (line 124)
write(a,filename,varargin{:})
Error in Spike_analysis_wrapper_forloop (line 17)
writetable(t,'Parameters spike.xlsx')
" I couldn't find how I can increase the number of inputs for the table."
What does that mean? Do you want to concatenate two tables? Or do you want to write two different tables to two different files?
"Undefined function 'write' for input arguments of type 'double'."
Hint: this line below isn't doing anything because you're not saving the output:
table(t)
What does that mean? Do you want to concatenate two tables? Or do you want to write two different tables to two different files?
The first one. I want to create one excel file that cointains all the tables created by the for loop. In other words, save the outputs of the function spike_analysis_1 for every spike in the same excel file.
Because the for loop was overwriting the data, I tried to include the code you wrote at the beginning in order to concatenate the tables
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', baseFileName)
%Call the function Spike_analysis
[Table_parameters_spike] = spike_analysis_file1(baseFileName);
writetable (Table_parameters_spike,'Parameters spike.xlsx')
end
But I got this error
Now reading spike1.mat
Table_parameters_spike =
2.749
Undefined function 'write' for input arguments of type 'double'.
Error in writetable (line 124)
write(a,filename,varargin{:})
Error in Spike_analysis_wrapper_forloop (line 14)
writetable (Table_parameters_spike,'Parameters spike.xlsx')
Not only the code didn't save the table but also the table took only the firs toutput of the function.
Did I explain it better?
That's not the code I wrote. I think you're talking about this code here:
In that code I produce a table named "Parameters_spike1". You're not producing that table.
Look up the documentation for writetable. It expects the first input to be a table. In this line below, you are producing a table but you're not saving it.
table(t)
Your loop is not saving the data on each iteration. Instead, you're overwriting the table on each iteration. 't' is being overwitten each time the loop iterates.
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', baseFileName)
%Call the function Spike_analysis
t=spike_analysis_file1(baseFileName) %<---- PROBLEM HERE
end
What is the output of spike_analysis()? A matrix, vector, cell array?
Is the output always the same size?
What is the output of spike_analysis()? A matrix, vector, cell array?
Is the output always the same size?
The outputs are all a vector. The file is converted to cell (struct2cell), and the outputs are obtained from each file. If the output keeps the same format as the file, the output is a cell. But I do not think so, right? Output is merely a number.
I've seen when I run the loop that the value of spike_analysis_file1(baseFileName) is always the first output of this function. I do not understand why the program only takes the first one instead of all the outputs written in the script.

Sign in to comment.

Categories

Find more on Programming 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!