dir function and importing data

7 次查看(过去 30 天)
Hey guys,
I have a folder called 'KR5' filled with 100 notepad files. Each notepad file has lots of data that I want. I want to read the data from each file and store it.
Here is my approach:
Using a for loop, read and store all of notepad file names into a variable "Direc".
Using another for loop, open each file and extract the data and store it. Here is the code I have so far:
clc;
clear all;
addpath(genpath(pwd));
Direc = dir('KR5');
for i = 1:length(Direc)
Direcname(i) = Direc(i).name;
end
I am getting this error:
??? In an assignment A(:) = B, the number of elements in A and B must be the same.
Can someone help me with this?

采纳的回答

Jan
Jan 2012-3-29
Direc(1).name is a [1 x N] char vector, also called a "string". You try to assign it to the scalar Direcname(1). But you cannot store a vector in a scalar.
You can store string in a cell:
...
Direcname{i} = Direc(i).name;
...
Consider the curly braces.
The loop can be omitted:
Direc = dir('KR5');
Direcname = {Direc(i).name};
Btw. clear all deletes all loaded functions from the memory. This does not have any advantage, but the reloading needs a lot of time. clc is not helpful here also.
Adding the current folder and all subfolders to the Matlab path might be useful for any purpose, but for the shown problem it does not help. Better use the absolute path of "KR5", see help fullfile.
  1 个评论
Sarah
Sarah 2012-3-29
Haha yeah it worked! I actually tried using the cell array earlier because I knew I was saving strings, but for some reason it didn't work for me...so I left that idea behind. Maybe my setup was wrong.
Anyways, thanks for the help :)

请先登录,再进行评论。

更多回答(1 个)

Geoff
Geoff 2012-3-29
In the loop, index Direcname using curly braces instead of brackets:
Direcname{i} = Direc(i).name;
This is because you're assigning to a cell-array.
Also, it's a good idea to define that cell array before the loop:
Direcname = {};
Or, better still (because you know the size):
Direcname = cell(1, length(Direc));
Since I'm giving aesthetic improvements, it's a good idea to avoid the use of 'i' as the loop variable since it is actually a reserved word (denoting the complex number, i ). There are 51 other single-letter alphas to choose from, and a plethora of more descriptive (more than one letter) options =)
Otherwise, it's looking good.
Cheers

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by