如何删除从零矩阵在MATLAB? [英] How to delete zeros from matrix in MATLAB?
本文介绍了如何删除从零矩阵在MATLAB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我的问题:
我在MATLAB一个 n×n个
矩阵。我想删除这个矩阵的所有零,并把它的行中的载体。对于 N = 4
,让说我有以下的矩阵:
A = [1 1 0 0
1 2 0 0
1 0 0 0
1 2 1 0];
如何获得以下内容:
V1 = [1];
V2 = [1 2];
V3 = [1];
V4 = [1 2 1];
我做了以下内容:
对于i = 1:尺寸(A,1)
TMP = A(I,:);
TMP(A(I,:)== 0)= [];
V {I} = tmp目录;
结束
解决方案
略快于 Divakar的回答:
= NZV arrayfun(@(n)的非零(A(N,:)),1:尺寸(A,1),uniformoutput',FALSE);
标杆
小矩阵
A =兰迪([0 3],100,200);
重复= 1000;抽搐
为计数= 1:重复
NZV = cellfun(@(x)的非零(X),mat2cell(A,一(1,尺寸(A,1)),尺寸(A,2)),'单',0);
结束
TOC抽搐
为计数= 1:重复
NZV = arrayfun(@(n)的非零(A(N,:)),1:尺寸(A,1),uniformoutput',FALSE);
结束
TOC所用时间是3.017757秒。
所用时间是2.025967秒。
大型矩阵
A =兰迪([0 3],1000,2000);
重复= 100;所用时间是11.483947秒。
所用时间是5.563153秒。
Here is my problem:
I have a nxn
matrix in matlab. I want to delete all the zeros of this matrix and put the rows of it in vectors. For n=4
, let say I have the following matrix:
A = [ 1 1 0 0
1 2 0 0
1 0 0 0
1 2 1 0 ];
How to get the following:
v1 = [ 1 1 ];
v2 = [ 1 2 ];
v3 = [ 1 ];
v4 = [ 1 2 1 ];
I did the following:
for i = 1:size(A, 1)
tmp = A(i, :);
tmp(A(i, :)==0)=[];
v{i} = tmp;
end
解决方案
Slightly faster than Divakar's answer:
nzv = arrayfun(@(n) nonzeros(A(n,:)), 1:size(A,1), 'uniformoutput', false);
Benchmarking
Small matrix
A = randi([0 3],100,200);
repetitions = 1000;
tic
for count = 1:repetitions
nzv =cellfun(@(x) nonzeros(x),mat2cell(A,ones(1,size(A,1)),size(A,2)),'uni',0);
end
toc
tic
for count = 1:repetitions
nzv = arrayfun(@(n) nonzeros(A(n,:)), 1:size(A,1), 'uniformoutput', false);
end
toc
Elapsed time is 3.017757 seconds.
Elapsed time is 2.025967 seconds.
Large matrix
A = randi([0 3],1000,2000);
repetitions = 100;
Elapsed time is 11.483947 seconds.
Elapsed time is 5.563153 seconds.
这篇关于如何删除从零矩阵在MATLAB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文