I need to import file Degree210B49_015.dat
and Degree210B50_005.dat
So, I do it with cell array like this
column_file_number = {'49_015' '50_005'};
for i = column_file_number
Name_file= strcat('Degree210B', i, '.dat');
Name_file
data(:,end+1)=importdata(Name_file);
end
However, the value returned by Name_file
is 'Degree210B49_015.dat'
. There are quotes.
And Because of this, I can't import the data.
How can I deal with it?
To understand the problem here, you need to understand how cell arrays work and how for
loops work.
The for
loop in the example works roughly the same as the following:
for index = 1:numel(column_file_number)
i = column_file_number(index);
There are two ways of accessing the entries of a cell array:
1) curly brackets: column_file_number{index}
will give you the element in location specified by index
. If index
is a vector containing several indices column_file_number{index}
will return a comma separated list of the entries at index
in the cell array. To retrieve the elements do something like [v1,v2] = column_file_number{[1,2]}
.
2) round brackets: column_file_number(index)
will give you a cell array containing the elements of column_file_number
at the indices specified by index
- even if index
only contains one element!
In the example the for
loop uses method 2 - that is the Name_file variable you get is a cell array of one element instead of a char element. So to solve the problem you can change line 5 to data(:,end+1)=importdata(Name_file{1});
or change line 3 to Name_file= ['Degree210B', i{1}, '.dat'];
.
The problem is a very simple problem, but I think it is quite common (I remember having the same problem when I first learned matlab), and understanding why the problem occurs and how to solve it is important to get fluent in matlab!