Reputation:
As an intermediate step to analysis I need to populate a variable called 'files' with the index of current iteration. So far I am doing it manually. I wouldn't like to do it manually for i=1:1000
so I am looking for some automation here, I experimented with many functions but nothing is working. Please help.
Thanks.
Given below is the code snipped I am running.
clear; clc;
for i=1:10
files{i}.data = {
{
['1.csv']
['2.csv']
['3.csv']
['4.csv']
['5.csv']
['6.csv']
['7.csv']
['8.csv']
['9.csv']
['10.csv']
}};
end
Update:
I am using this script
clear; clc;
wdir = 'path\';
all_files = 10;
for i=1:10
files{i}.data = {
{
cellstr(strcat(wdir,num2str((1:all_files).'),'.csv'))
}};
end
Everything is good about this script except the string concat function, It generates space between path and file number for 1..9 files and file no. 10 is perfect. Please help me to fix this. I am getting something like this.
Upvotes: 1
Views: 171
Reputation: 1
Long in short, you could try command 'eval' in Matlab. Idk if you are familiar with python, basically 'eval' in Matlab does the same as what 'exec' does in python.
A very simple example below:
for i=1:10
eval(['f',num2str(i),'=[];'])
end
you'll get f1, f2, f3...... all the way to f10, while they are all empty matrix.
Upvotes: -1
Reputation: 26014
You may combine compose and cellstr to obtain the desired cell array:
>> wdir = 'path\';
>> X = 1:10;
>> formatSpec = "%s%d.csv";
>> cellstr(compose(formatSpec,wdir,X)).'
ans =
10×1 cell array
{'path\1.csv' }
{'path\2.csv' }
{'path\3.csv' }
{'path\4.csv' }
{'path\5.csv' }
{'path\6.csv' }
{'path\7.csv' }
{'path\8.csv' }
{'path\9.csv' }
{'path\10.csv'}
For releases of MATLAB prior to R2016b you may use a loop and sprintf:
>> wdir = 'path\';
>> X = 1:10;
>> formatSpec = '%s%d.csv';
>> arrayfun(@(x) sprintf(formatSpec,wdir,x),X,'un',0).'
ans =
10×1 cell array
{'path\1.csv' }
{'path\2.csv' }
{'path\3.csv' }
{'path\4.csv' }
{'path\5.csv' }
{'path\6.csv' }
{'path\7.csv' }
{'path\8.csv' }
{'path\9.csv' }
{'path\10.csv'}
Upvotes: 3
Reputation: 1264
If I understand the question correctly it would be something like this:
files_length = 1000;
for id=1:files_length
files{id}.data = {sprintf('%d.csv', id)};
end
Upvotes: 0