Question

I have a 3D large Matrix, the first index (x) represents frequency and the second and third indexes (y and z) are the indexes of the data. I want to print the data for each index for all the frequencies, then print a | char and a new line char. I do this in the following way:

% S is a 3D matrix of size (x,y,z), where y=z and x>>y
N=size(S,2);
MM=real(S);
for mi=1:N
    for mj=1:N
        fprintf(fid,"%.16g ",MM(:,mi,mj));
        fprintf(fid,"|\n");
    end
end

But for large matrices this is very slow. Is there a way to speed up the process?

This is done in octave, which means that a Matlab solution will work as well.

Was it helpful?

Solution

If I understood your input data correct, your loop is equivalent to:

fprintf(fid,[repmat('%.16g ',1,size(S,1)) '|\n'],permute(real(S),[1,3,2]));

fprintf starts over using the format string when it reaches the end. The permute is necessary to preserve the order from your code.

OTHER TIPS

Here is a general approach to speed things up:

  1. Calculate everything you want to calculate, store each result as a number or a string
  2. Print the result to file in 1 go
m=zeros(3,4,5);
[x,y,z]=size(m);
for k=1:x
    for l=1:y
        dlmwrite('D:\test.txt',m(k,l,:),'-append','delimiter',' ','newline','pc');
    end
    dlmwrite('D:\test.txt',[' '],'-append','newline','pc');
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top