【问题标题】:Solution for saving array data in text file line by line in MatlabMatlab中逐行保存文本文件中数组数据的解决方法
【发布时间】:2019-11-24 20:43:06
【问题描述】:
[r1 c1]= size(cluster_head);
r1
fid=fopen('na.txt','w');
for f=1:r1
    f
    for m = 1:c1
        %value of cluster in chrosome
        a= cluster_head(1,m);
        temp = find(neighbors1(cluster_head(1,m),:));
        disp('neighbour')
        temp
        [r c]= size(temp);
        k(1,1)=cluster_head(1,m);
        for n=2:c+1
            if(temp(1,n-1)~=k(1,1))
                k(f,n)= temp(1,n-1);
                save solution.txt k(f,n) -ASCII
            end
        end
        fprintf('%d Iterations completed\n',m);
    end
end

需要k(f,n)逐行保存在文本文件中。 但是 solution.txt 只存储第一行中的最后一个解决方案值,覆盖所有其他或以前的解决方案。

【问题讨论】:

标签: matlab save text-files


【解决方案1】:

这是因为每次调用 save 都会用列出的变量值覆盖文件内容,即代码中的 k(f,n)。所以最后留在文件中的是满足if条件的k的最后一个元素。

如果您想使用save 保存所有数据,则需要将数据收集到一个变量中并调用一次save。请看以下示例:

%% save a row vector to file
row = 1:4;
save row.txt row -ascii

1.0000000e+00 2.0000000e+00 3.0000000e+00 4.0000000e+00

%% 
col = (1:4)';
save col.txt col -ascii

1.0000000e+00
2.0000000e+00
3.0000000e+00
4.0000000e+00

%% save a matrix to file
mat = reshape(1:4, [2, 2]);
save mat.txt mat -ascii

1.0000000e+00 3.0000000e+00
2.0000000e+00 4.0000000e+00

%% save a matrix as column, with columns precedency
mat2 = mat(:);
save mat_colsfirst.txt mat2 -ascii

1.0000000e+00
2.0000000e+00
3.0000000e+00
4.0000000e+00

%% save a matrix as column, with rows precedency
mat3 = mat';
mat3 = mat3(:);
save mat_rowsfirst.txt mat3 -ascii

1.0000000e+00
3.0000000e+00
2.0000000e+00
4.0000000e+00

另一个选项是使用fprintf,这有点复杂,因为您需要保留文件句柄。但是使用 fprintf 您可以将新行附加到文件中。另一个优点是您可以控制结果的格式:

filename = 'mat2.txt';
% open the file
% 'w': Open or create new file for writing. Discard existing contents, if any.
% 'n': Your system byte ordering (native)
% 'US-ASCII': ASCII character encoding
fileID = fopen(filename, 'w', 'n', 'US-ASCII');
mat = reshape(1:4, [2, 2]);
for jj=1:2
    for ii=1:2
        % write one of mat elements with 1 digit after floating point in a new line
        fprintf(fileID, '%.1f\n', mat(ii, jj));
    end
end
% close the file
fclose(fileID);
% display file contents in command window
type(filename)

1.0
2.0
3.0
4.0

【讨论】:

  • 请在临时变量中给我更多帮助,我得到 2 3 5 并且我在循环之前修复了 K(1,1)。我希望 K(1,1) 元素将元素临时存储在一行中。其实我是 Matlab 的初学者。
  • 对不起@HammadShafiq,我真的不听。尝试以不同的方式描述问题。是临时变量还是文件内容有问题?
  • 亲爱的我终于解决了这个问题。感谢您的帮助。
猜你喜欢
  • 2014-02-18
  • 2012-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-13
相关资源
最近更新 更多