如何在.mat文件行或列单元格矩阵中追加 [英] How to append in .mat file row or columnwise cellmatrix

查看:439
本文介绍了如何在.mat文件行或列单元格矩阵中追加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个仿真,在其中生成巨大的2d稀疏矩阵,因此我使用FIND函数仅将非零值及其索引存储起来.

现在,对于for循环的每次迭代,我都会生成这样的矩阵,并且由于它们的长度都不同,因此我使用单元数组来存储这些配置.但是对于大型仿真,即使是压缩的单元格数组格式也超出了其内存限制,因此我想在运行代码时编写这些单元格数组,即每次迭代都将一个新元素添加到现有的mat文件中.

例如

for n=1:10  
A=rand(5);  
[i,j,vals]=find(A);  
data={[i,j,vals]};  
save('data','data','-append');  
end

这里我的最终目标是要创建一个Mat文件,其中数据"中的元素数为10.但是由于内存问题,我无法将其保存在for循环之外,我想生成数据{n}并将其追加到专栏式增长的时尚.最终给了我数据{10}.

我尝试使用MATFILE,但是它给我一个错误,即它不适用于{},因此不适用于单元格数组.

谢谢你, 尼丁

解决方案

只要不尝试索引实际单元格,就可以将matfile与单元格一起使用.请记住,单元仍然是数组,因此您可以使用数组索引访问每个单元.例如:

>> x = {'this', 'is', 'an', 'example'};
>> x{4}

ans =

example

>> x(4)

ans = 

    'example'

以下仅初始化数据.确保使用'-v7.3'标签保存它,以便它支持有效的部分保存和加载.

data = {};
save('data.mat', 'data', '-v7.3');

现在您可以使用matfile访问数据

mf = matfile('data.mat', 'Writable', true);
for n=1:10  
   A=rand(5);  
   [i,j,vals]=find(A);  
   data={[i,j,vals]};
   mf.data(end+1, 1) = data;
end

参考: matfile文档

I am running a simulation where i generate huge 2d sparse matrices and hence i use FIND function to only store nonzero values with their indices.

Now for each iteration of for loop i generate such matrix and because they are all of different length I use cell-array to store these configurations. But for large simulations even squeezed-off format of cell-array crosses its limits of memory and hence i want to write these cell-array while running the code i.e. for each iteration append a new element into existing mat file.

for e.g.

for n=1:10  
A=rand(5);  
[i,j,vals]=find(A);  
data={[i,j,vals]};  
save('data','data','-append');  
end

Here my final goal is to have a mat file where number of elements in "data" are 10. but i because of memory issues i cant save it outside the for loop i want to generate data{n} and append it in columnwise growing fashion. eventually giving me data{10}.

I tried to use MATFILE but it gives me error that it doesnt work with {} hence not working with cell arrays.

Thank you, Nitin

解决方案

You can use matfile with cells as long as you are not trying to index into the actual cells. Remember that cells are still arrays, so you can access each cell using array indexing. For example:

>> x = {'this', 'is', 'an', 'example'};
>> x{4}

ans =

example

>> x(4)

ans = 

    'example'

The following just initializes the data. Make sure to save it with the '-v7.3' tag, so that it supports efficient partial saving and loading.

data = {};
save('data.mat', 'data', '-v7.3');

Now you can access your data with the matfile

mf = matfile('data.mat', 'Writable', true);
for n=1:10  
   A=rand(5);  
   [i,j,vals]=find(A);  
   data={[i,j,vals]};
   mf.data(end+1, 1) = data;
end

Reference: matfile documentation

这篇关于如何在.mat文件行或列单元格矩阵中追加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆