1

I have loaded certain arrays in matlab and I want to take means and stuff, but my problem is that 'M' which is a variable( it is in the code that i have attached) is treated as a char rather than as an array(which it actually is). How to make use of M, the array instead of M, the char?

kk=[];
files = dir('*.dat');
for i=1:length(files)
    eval(['load ' files(i).name])
    M=files(i).name;
    load(M)
    p=mean(M,2);
    kk=[kk p];
end
mn= mean(kk,2);
Shai
  • 111,146
  • 38
  • 238
  • 371
Shash
  • 11
  • 2
  • have you tried `load(M(:))` or `load(M(:)')`? Also what's the point of the `eval` line or is that what you're trying to get rid of? – Dan Jun 24 '13 at 06:53
  • See [this question](http://stackoverflow.com/questions/17030172/load-multiple-mat-files-for-processing) - it is quite similar. – user2469775 Jun 24 '13 at 07:52

2 Answers2

2

Several comments:

  1. You can load into a variable M instead of assigning the file name to M

    >> M = load( files(ii).name ); % load the file into a matrix M
    
  2. If you want to compute the mean of all numbers stored in all the files, then mean( [mean(M1,2) mean(M2,2) ...] ) is not necessarily the mean what you want.
    If there is a different number of columns in the different matrices, then you are not computing the desired quantitiy. Make sure you are computing the right quantity you are looking for.

  3. Do not use eval: it is unnecessary, makes the code difficult to read and hard to maintain and debug.

  4. Do not grow an array inside a loop: kk = [kk p];. This kind of behavior kills Matlab's performance, because it needs to re-allocate kk at each iteration. Pre-allocate the memory required for kk before the loop - you'll see a significant speedup.

  5. In Matlab, it is best not to use i as a variable name.

Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
0

Why don't use importdata function with some text processing for the filename:

M=importdata(['/path/to/file/' num2str(j) '.dat'])

or

M=load(['/path/to/file/' num2str(j) '.dat'])

Also, you can try dlmread in your case. I think load is more proper for MAT files. Here is a comparison of different ways:

http://www.mathworks.nl/help/matlab/import_export/ways-to-import-text-files.html

freude
  • 3,632
  • 3
  • 32
  • 51