构造不同长度的矢量
问题描述:
我想知道3维空间中的零点个数row
和column
。问题是我每次都得到不同长度的输出向量(例如行),因此会发生尺寸错误。 我尝试:构造不同长度的矢量
a (:,:,1)= [1 2 0; 2 0 1; 0 0 2]
a (:,:,2) = [0 2 8; 2 1 0; 0 0 0]
for i = 1 : 2
[row(:,i) colum(:,i)] = find(a(:,:,i)==0);
end
答
可以使用线性索引:
a (:,:,1) = [1 2 0; 2 0 1; 0 0 2];
a (:,:,2) = [0 2 8; 2 1 0; 0 0 0];
% Answer in linear indexing
idx = find(a == 0);
% Transforms linear indexing in rows-columns-3rd dimension
[rows , cols , third] = ind2sub(size(a) ,idx)
更多的话题可以Matlab's help
+0
它运作良好。尽管制作单元格会很有用。 –
+0
我不确定你的意思是“制造细胞”。在单个单元格中创建'rows','cols'和'third'?在三个单独的单元阵列?单个矩阵的单元格? – Zep
答
让我们假设你的矩阵的格式为n乘M-通过-P。 在你的情况
N = 3;
M = 3;
P = 2;
这意味着行和coloms的最大长度从搜索(如果所有项目均为零)是N*M=9
所以,一个可能的解决方案是
%alloc output
row=zeros(size(a,1)*size(a,2),size(a,3));
colum=row;
%loop over third dimension
n=size(a,3);
for i = 1 : n
[row_t colum_t] = find(a(:,:,i)==0);
%copy your current result depending on it's length
row(1:length(row_t),i)=row_t;
colum(1:length(colum_t),i)=colum_t;
end
但是,如果将结果传递到下一个函数/脚本,则必须记住对非零元素进行操作。
我会去为Zep矢量化解决方案。至于更大的矩阵a
它更有记忆效率,我相信它必须更快。
使用电池来存储值被发现。 – OmG