How can I load data from a folder in a variable using a for loop?
显示 更早的评论
Hi there, I am new to MATLAB and programming in general. I'm using code from Github for a research project in which participants draw where they experiencing bodily sensations (e.g., increasing heart rate) in the context of a specific emotion.
I want to load the mouse movements of my subjects into the variable "data". While doing so, it seems I get stuck in a for-while loop. It seems that the variable "data" is not created (at least it does not show up in my Workspace). I do not receive any error messages.
I don't know what could go wrong and where to look for solutions. Am I missing something?
I have copy pasted the code below.
% get a list of subjects
basepath='demo_subjects'; % folder where subjects are
subjects=dir([basepath '\D:\MATLAB\embody-master\embody_presentation_jan2023\*']);
% the base image used for painting (in our case only one sided since we
% subtract values)
base=uint8(imread('base.png'));
base2=base(10:531,33:203,:); % single image base
labels={'Neutral'
'Fear'
'Anger'
'Disgust'
'Sadness'
'Happiness'
'Surprise'
'Anxiety'
'Love'
'Depression'
'Contempt'
'Pride'
'Shame'
'Jealousy'
};
mask=imread('mask.png');
% for each subject, load data
for s=1:length(subjects)
% skip dot and dotdot folders
if(strcmp(subjects(s).name(1),'.'))
continue; end
I think Data Loading part is where it goes wrong. For completeness I have pasted the entire for-while loop (I feel like it's quite a long loop?).
%% Data loading
% let's load the subject's answers into a variable
data=load_subj([basepath '/' subjects(s).name],2);
NC=length(data); % number of conditions
%% Painting reconstruction
% 'data' now contains all mouse movements. What we need are the mouse
% locations while the button was pressed (i.e. during painting)
% Furthermore, the painting tool has a brush size. We recreate that
% using image filter
for n=1:NC
T=length(data(n).paint(:,2)); % number of mouse locations
over=zeros(size(base,1),size(base,2)); % empty matrix to reconstruct painting
for t=1:T
y=ceil(data(n).paint(t,3)+1);
x=ceil(data(n).paint(t,2)+1);
if(x<=0) x=1; end
if(y<=0) y=1; end
if(x>=900) x=900; end % hardcoded for our experiment, you need to change it if you changed layout
if(y>=600) y=600; end % hardcoded for our experiment, you need to change it if you changed layout
over(y,x)=over(y,x)+1;
end
% Simulate brush size with a gaussian disk
h=fspecial('gaussian',[15 15],5);
over=imfilter(over,h);
% we subtract left part minus right part of painted area
% values are hard-coded to our web layout
over2=over(10:531,33:203,:)-over(10:531,696:866,:);
resmat(:,:,n)=over2;
end
%% store result (commented)
save(['preprocessed' subjects(s).name '_preprocessed.mat'],'resmat')
%% visualize subject's data
M=max(abs(resmat(:))); % max range for colorbar
NumCol=64;
hotmap=hot(NumCol);
coldmap=flipud([hotmap(:,3) hotmap(:,2) hotmap(:,1) ]);
hotcoldmap=[
coldmap
hotmap
]
% note that - for statistical maps - if you want to hide non
% significant values and show them as black, you need to tweak the
% colormap so that you have more rows of black between around the
% non-significant interval.
% As an example if we had a threshold, uncomment the below
if(0)
th=0.2*M; % just an example threshold, since this is not a statistical map
non_sig=round(th/M*NumCol); % proportion of non significant colors
hotmap=hot(NumCol-non_sig);
coldmap=flipud([hotmap(:,3) hotmap(:,2) hotmap(:,1) ]);
hotcoldmap=[
coldmap
zeros(2*non_sig,3);
hotmap
]
end
% visualize all responses for each subject into a grid of numcolumns
plotcols = 7; %set as desired
plotrows = ceil((NC+1)/plotcols); % number of rows is equal to number of conditions+1 (for the colorbar)
for n=1:NC
figure(s)
subplot(plotrows,plotcols,n)
imagesc(base2);
axis('off');
set(gcf,'Color',[1 1 1]);
hold on;
over2=resmat(:,:,n);
fh=imagesc(over2,[-M,M]);
axis('off');
axis equal
colormap(hotcoldmap);
set(fh,'AlphaData',mask)
title(labels(n),'FontSize',10)
if(n==NC)
subplot(plotrows,plotcols,n+1)
fh=imagesc(ones(size(base2)),[-M,M]);
axis('off');
colorbar;
% save a screenshot, useful for quality control (commented)
saveas(gcf,[subjects(s).name '.png'])
end
end
end
The code uses a function "load_subj" which, I think, reads the list of conditions that the subject was presented (these are stored in a txt file) and "connects" it to the correct mouse movement data (stored in several csv files in the subject folder).
function data=load_subj(folder,option)
list=csvread([folder 'presentation.txt']);
N=length(list);
if(option==0)
disp('here')
for n=0:N-1
file=[folder '/' num2str(n) '.csv'];
fid = fopen(file);
line=textscan(fid,'%s','CollectOutput',1,'Delimiter',';');
data(:,n+1)=line{1};
end
data=data';
end
if(option==1)
disp('option 1 not implemented')
end
if(option>=2)
for n=0:N-1
file=[folder '\' num2str(n) '.csv'];
line=dlmread(file,',');
delim=find(-1==line(:,1));
data(n+1).mouse=line(1:delim(1)-1,:);
data(n+1).paint=line((delim(1)+1):(delim(2)-1),:);
data(n+1).mousedown=line((delim(2)+1):(delim(3)-1),:);
data(n+1).mouseup=line((delim(3)+1):end,:);
end
end
1 个评论
You might find that tidying up the code will help. A few tips:
** Always always always always always FCLOSE() every file that you FOPEN() !!!!
** Replace text concatenation of paths and filenames with FULLFILE(). For example, replace this:
[folder,'presentation.txt']
with
fullfile(folder,'presentation.txt')
** Align your code consistently, which helps when writing and debugging code. The MATLAB editor can do this for you: select all code, then press ctrl+i
** Note you can remove the dot-directories before the loop:
S = dir(..);
S(strncmp({S.name},'.',1)) = [];
** As the documentation recommends, consider replacing DLMREAD() with READMATRIX(), and TEXTSCAN() with READCELL() or READLINES() or whatever suits your data files.
** Preallocate arrays before loops: https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html
Now lets start debugging: please show us the value of length(subjects)
回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Variables 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!