delete zeros rows and columns

I try this code to delete all row and column with all zero values in them. It simply works for deleting the columns with all zero values abut it does not work for rows! Can anybody please help me?
data=[0 0 0 0 0 0 0 0; 0 0 2 3 4 0 1 0; 0 0 1 2 3 0 0 0];
data( all( ~any( data), 2 ), : ) = []; % removes all rows with all zero
data( :, all( ~any( data ), 1 ) ) = []; % and columns
I mean the first line (% removes all rows with all zero) does not work!

 Accepted Answer

data( ~any(data,2), : ) = []; %rows
data( :, ~any(data,1) ) = []; %columns

14 Comments

Thanks, for your instant reply.
Thank you for helping ..
What does the 2 and 1 stand for ? How does this function work so i can use it in diverse situations ? Many thanks in advance !
"B = any(A,dim) tests elements along dimension dim. The dim input is a positive integer scalar."
So, specifying dim of 1 tells it to act along the first dimension, reducing it to a singleton. dim of 2 tells it to act along the second dimension, reducing that to a singleton.
So can I just use
data( ~any(data,1), : ) = []; %rows
data( :, ~any(data,1) ) = []; %columns
Thanks :)
Sorry, never mind! I got it.
lieverd
Is this faster than the "converse" data = data(any(data,2),:) ; ?
I have seen a few timing tests that tend to suggest that selection such as data = data(any(data,2),:) is faster than deletion such as data( ~any(data,2), : ) = [];
can this be done in 1 go so i remove for example all columns with zeros, and after i want to remove the rows that contained a zero but doesnt anymore?

Mads Albertson:

Should the column be removed if it contains at least one zero, or should it be removed only if it is all zero? Based on your wanting to remove corresponding rows, it would only seem to make sense if it was at least one zero (otherwise you would be removing all rows)

It might be possible to write a single expression that removed the rows and columns, but it would have to evaluate the test for zero twice, except possibly it could be written as a single line of code if it were permitted to use auxiliary functions. The version that evaluates the zero test twice twice is

data = data(all(data, 2), all(data, 1));
it doesnt need to be a full row if 0's, just if one occour in a row/ column, but your code works perfect
thx Walter Roberson
Dears,
while running this matlab code, the transpose of the matrix teste s not working. Can u please suggest me if there is updated code for running a contourf for R2024b. [Error in (line 145).... contourf(linspace(0,3,42),linspace(0.0,0.1,40),teste','LineStyle','-','LineWidth',0.2)]
contourf(linspace(0,3,42),linspace(0.0,0.1,40),teste','LineStyle','-','LineWidth',0.2)
%%
when I define the teste matrix it is in line 140, teste = zeros(42,40);
I got anather problem in in line 160, mc6 = set(m1,'parameters',c6);
%%below I post the array sizes, the connection between the for loop and the contourf(). could you check if the matrix teste is correctly defined. and suggest me where the problem to fix. Thanks
%%%
clear
close all
clc
%%
% Choose shock variance. If solution order = 1, high_var is ok.
label_1={1,'low_var'
2,'high_var'};
% Choose exogenous switching, endogenous switching or fixed regimes.
label_2={1,'fixed_regime_M'
2,'ms_regimes'
3,'ms_endog_regimes'
4,'fixed_regime_F'};
% Choose taxation scheme
label_3={1,'non-distortionary'
2,'distortionary'};
% Read the models and their calibrations. Change labels as disired!
m0=rise('rsa_ms',...
'rise_flags',...
struct('varmodel',label_1{2,1},...
'msmodel', label_2{3,1},...
'taxdistortionary', label_3{1,1}),...
'irf_anticipate',false);
Unrecognized function or variable 'rise'.
% Solve the model with baseline calibration; 1st order. Solvers: 'mfi', 'mn', 'mnk', 'fwz'. See issue 108.
% "The newton algorithm mn is locally stable around an equilibrium while the main strength of mfi is to handle large systems."
m1=solve(m0,'solve_shock_horizon',0,'solve_order',1,...
'solve_check_stability',false); %'solver','mn','solve_perturbation_type','mw' or 'frwz'
%[malt,stab]=solve_alternatives(m0);
% 2ns order solution
%m2nd=solve(m1,'solve_order',2,'solve_derivatives_type','automatic');
%m2nd.print_solution({'Pi','Y','C','b','R','sp','Welfare','CE'});
% Check the stability of the system
%m1.is_stable_system % Stability is denoted by 1 (0 means unstable)
% Print solution and steady state values
% m1.print_solution() % for all variables
% print solution for a subset of variables only
m1.print_solution({'Pi','Y','C','B','R','sp','Welfare','CE','Q'});
%% QUICK IRFs
myirfs=irf(m1,'irf_periods',24,'irf_shock_sign',1);
var_list={'log_y','C','pi_ann','B_nominal','B','sp','i_ann','r_real_ann','Welfare'};
figure('name','Impulse responses to a fiscal shock');
for ii=1:numel(var_list)
subplot(3,3,ii)
reg1=myirfs.eps_G.(var_list{ii}).data(:,1);
reg2=myirfs.eps_G.(var_list{ii}).data(:,2);
plot(reg1);
hold on
plot(reg2);
title(var_list{ii})
axis tight
end
%% STABILITY & SOLUTIONS w.r.t. BASELINE CALIBRATION
% SELECTED PARAMETERS: t_ss, delta_B, abc_tp_1_2, rho_G, rho_T, kappa.
grid_size = 20;
t_ss_vec = linspace(0,0.03,grid_size);
delta_B_vec = linspace(0,1.00,grid_size);
rho_G_vec = linspace(0,0.90,grid_size);
rho_T_vec = linspace(0,0.90,grid_size);
kappa_vec = linspace(0,0.98,grid_size);
prob_vec = linspace(0,0.20,grid_size);
solution_mat = NaN(grid_size,6);
stab_mat = NaN(grid_size,6);
%% Loop for just one parameter
for j = 1:grid_size
c = struct('delta_B_abc_1', delta_B_vec(j)); % CHANGE THIS LINE FOR DESIRED PARAMETER
mc = set(m1,'parameters',c);
ms=solve(mc,'solve_order',1,'solve_check_stability',false,'solve_perturbation_type','mw');
solution_mat(j,1) = ms.nsols;
disp(j)
end
%% Loop for two parameter
grid_size = 20;
delta_B_vec = linspace(0, 0.05, grid_size);
phi_pi_vec = linspace(0, 3.00, grid_size+1);
for j = 1:(grid_size+1)
for i = 1:grid_size
c = struct('delta_B_abc_1', delta_B_vec(i),'phi_pi_abc_1', phi_pi_vec(j)); % _abc_1
mc = set(m0,'parameters',c);
ms=solve(mc,'solve_order',1);
if ms.nsols == 0
% d_mat(j,i) = NaN;
% pi_mat(j,i) = NaN;
% var_mat(j,i) = NaN;
solution_mat(j,i) = 0;
stab_mat(j,i) = 0;
else
% simdata0 = simulate(ms,'simul_regime',1,'simul_order',1,'simul_periods',1000);
% if isempty(simdata0)
% d_mat(j,i) = NaN;
% pi_mat(j,i) = NaN;
% stab_mat(j,i) = 0;
% solution_mat(j,i) = 0;
% var_mat(j,i) = NaN;
% else
% tempirf=irf(ms,'irf_periods',24,'irf_shock_sign',1);
% d_mat(j,i) = (tempirf.eps_G.B.data(4,1) - tempirf.eps_G.B.data(13,1)) > 0;
% pi_mat(j,i) = mean(simdata0.Pi.data);
% var_mat(j,i) = var(simdata0.Pi.data);
solution_mat(j,i) = ms.nsols;
stab_mat(j,i) = ms.is_stable_system;
% end
end
end
disp((j))
end
%figure(1)
%s = pcolor(stab_mat');
%s.LineStyle = '-';
%colormap(gray)
%teste = zeros(42,40);
%% Plot stability
figure(1)
set(1,'Color','w')
contourf(linspace(0,3,42),linspace(0.0,0.1,40),teste','LineStyle','-','LineWidth',0.2)
colormap(gray)
set(gca,'fontsize',10)
xlabel('Taylor Rule Parameter - $\phi_\pi$','interpreter','latex')
ylabel('Fiscal Parameter - $\delta_B$','interpreter','latex')
set(gca,'TickLabelInterpreter','latex')
%yticklabels([0.00 0.02 0.04 0.06 0.08 1.00])
set(gca,'fontsize',12)
line1 = '';
%line2 = 'Fixed Parameters';
%line2 = 'Exogenous Switching';
line2 = 'Endogenous Switching';
title(sprintf('\\begin{tabular}{c} %s %s %s \\end{tabular}',line1,'\\',line2),...
'interpreter','latex')
x0=1000;
y0=300;
width=350;
height=300;
set(1,'position',[x0,y0,width,height]);
%% Loop all selected parameters
for j = 1:grid_size
% 'c' stands for 'calibration'
c1 = struct('t_ss', t_ss_vec(j));
c2 = struct('delta_B_abc_1', delta_B_vec(j));
c3 = struct('rho_G', rho_G_vec(j));
c4 = struct('rho_T', rho_T_vec(j));
c5 = struct('kappa', kappa_vec(j));
c6 = struct('abc_tp_1_2', prob_vec(j));
% 'mc' stands for 'model with new calibration'
mc1 = set(m1,'parameters',c1);
mc2 = set(m1,'parameters',c2);
mc3 = set(m1,'parameters',c3);
mc4 = set(m1,'parameters',c4);
mc5 = set(m1,'parameters',c5);
mc6 = set(m1,'parameters',c6);
% Solve
ms1=solve(mc1,'solve_order',1,'solve_check_stability',false);
ms2=solve(mc2,'solve_order',1,'solve_check_stability',false);
ms3=solve(mc3,'solve_order',1,'solve_check_stability',false);
ms4=solve(mc4,'solve_order',1,'solve_check_stability',false);
ms5=solve(mc5,'solve_order',1,'solve_check_stability',false);
ms6=solve(mc6,'solve_order',1,'solve_check_stability',false);
% Has a solution? Is stable?
solution_mat(j,1) = ms1.nsols;
solution_mat(j,2) = ms2.nsols;
solution_mat(j,3) = ms3.nsols;
solution_mat(j,4) = ms4.nsols;
solution_mat(j,5) = ms5.nsols;
solution_mat(j,6) = ms6.nsols;
disp(j)
end
rise() is an undefined function.

Sign in to comment.

More Answers (2)

Geoff
Geoff on 31 May 2012
Yeah you did too much!
% Remove zero rows
data( all(~data,2), : ) = [];
% Remove zero columns
data( :, all(~data,1) ) = [];

5 Comments

Thanks a lot, You guys really saved me from feeling crazy!
Note: logically all(~data) and ~any(data) work out the same. The only logical difference is in the amount of work done, with ~any(data) taking less work than all(~data)
The reason that ~any(data) takes less work than all(~data) is that ~data requires negating every element in data. Both any(x) and all(x) are able to terminate early; any(x) terminates as soon as it sees a nonzero and all(x) terminates as soon as it sees a zero.
Giuseppe
Giuseppe on 4 Aug 2018
Edited: Giuseppe on 4 Aug 2018
Guys, what if we would need to remove zero rows from the first occurence onwards? E.g. at same point all rows are zeros but they may be non zero afterwards still you want to eliminate all rows from the first zero occurence?
Thank you, it worked :)
Can someone explain why this works.
Regards,
Olaf

Sign in to comment.

I'm new to MATLAB, I want to delete the entire rows and columns which contain all of ones in a binary image.I want to keep rows and columns if that contain only single zero. Any tips on how to go about doing this? Thanks
>> binaryimage
binaryimage =
33×35 logical array
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 0 0 1
1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 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1 0 0 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
I want to remove rows and columns that contains all of ones

6 Comments

binaryimage(all(binaryimage,2),:) = [];
binaryimage(:, all(binaryimage,1)) = [];
Thanks a lot.its works well.thanks for help.its makes my day.
I want to crop a binary image by using segmentation algorithm.If I want to solve this problem by doing segmentation,how can I implement the code?
how do I find source code/algorithms of any existing papers that they implement?
How do I crop every single character automatically in matlab by using segmentation?
Dears,
while running this matlab code, the transpose of the matrix teste s not working. Can u please suggest me if there is updated code for running a contourf for R2024b. [Error in (line 145).... contourf(linspace(0,3,42),linspace(0.0,0.1,40),teste','LineStyle','-','LineWidth',0.2)]
contourf(linspace(0,3,42),linspace(0.0,0.1,40),teste','LineStyle','-','LineWidth',0.2)
%%
when I define the teste matrix it is in line 140, teste = zeros(42,40);
I got anather problem in in line 160, mc6 = set(m1,'parameters',c6);
%%below I post the array sizes, the connection between the for loop and the contourf(). could you check if the matrix teste is correctly defined. and suggest me where the problem to fix. Thanks
%%%
clear
close all
clc
%%
% Choose shock variance. If solution order = 1, high_var is ok.
label_1={1,'low_var'
2,'high_var'};
% Choose exogenous switching, endogenous switching or fixed regimes.
label_2={1,'fixed_regime_M'
2,'ms_regimes'
3,'ms_endog_regimes'
4,'fixed_regime_F'};
% Choose taxation scheme
label_3={1,'non-distortionary'
2,'distortionary'};
% Read the models and their calibrations. Change labels as disired!
m0=rise('rsa_ms',...
'rise_flags',...
struct('varmodel',label_1{2,1},...
'msmodel', label_2{3,1},...
'taxdistortionary', label_3{1,1}),...
'irf_anticipate',false);
Unrecognized function or variable 'rise'.
% Solve the model with baseline calibration; 1st order. Solvers: 'mfi', 'mn', 'mnk', 'fwz'. See issue 108.
% "The newton algorithm mn is locally stable around an equilibrium while the main strength of mfi is to handle large systems."
m1=solve(m0,'solve_shock_horizon',0,'solve_order',1,...
'solve_check_stability',false); %'solver','mn','solve_perturbation_type','mw' or 'frwz'
%[malt,stab]=solve_alternatives(m0);
% 2ns order solution
%m2nd=solve(m1,'solve_order',2,'solve_derivatives_type','automatic');
%m2nd.print_solution({'Pi','Y','C','b','R','sp','Welfare','CE'});
% Check the stability of the system
%m1.is_stable_system % Stability is denoted by 1 (0 means unstable)
% Print solution and steady state values
% m1.print_solution() % for all variables
% print solution for a subset of variables only
m1.print_solution({'Pi','Y','C','B','R','sp','Welfare','CE','Q'});
%% QUICK IRFs
myirfs=irf(m1,'irf_periods',24,'irf_shock_sign',1);
var_list={'log_y','C','pi_ann','B_nominal','B','sp','i_ann','r_real_ann','Welfare'};
figure('name','Impulse responses to a fiscal shock');
for ii=1:numel(var_list)
subplot(3,3,ii)
reg1=myirfs.eps_G.(var_list{ii}).data(:,1);
reg2=myirfs.eps_G.(var_list{ii}).data(:,2);
plot(reg1);
hold on
plot(reg2);
title(var_list{ii})
axis tight
end
%% STABILITY & SOLUTIONS w.r.t. BASELINE CALIBRATION
% SELECTED PARAMETERS: t_ss, delta_B, abc_tp_1_2, rho_G, rho_T, kappa.
grid_size = 20;
t_ss_vec = linspace(0,0.03,grid_size);
delta_B_vec = linspace(0,1.00,grid_size);
rho_G_vec = linspace(0,0.90,grid_size);
rho_T_vec = linspace(0,0.90,grid_size);
kappa_vec = linspace(0,0.98,grid_size);
prob_vec = linspace(0,0.20,grid_size);
solution_mat = NaN(grid_size,6);
stab_mat = NaN(grid_size,6);
%% Loop for just one parameter
for j = 1:grid_size
c = struct('delta_B_abc_1', delta_B_vec(j)); % CHANGE THIS LINE FOR DESIRED PARAMETER
mc = set(m1,'parameters',c);
ms=solve(mc,'solve_order',1,'solve_check_stability',false,'solve_perturbation_type','mw');
solution_mat(j,1) = ms.nsols;
disp(j)
end
%% Loop for two parameter
grid_size = 20;
delta_B_vec = linspace(0, 0.05, grid_size);
phi_pi_vec = linspace(0, 3.00, grid_size+1);
for j = 1:(grid_size+1)
for i = 1:grid_size
c = struct('delta_B_abc_1', delta_B_vec(i),'phi_pi_abc_1', phi_pi_vec(j)); % _abc_1
mc = set(m0,'parameters',c);
ms=solve(mc,'solve_order',1);
if ms.nsols == 0
% d_mat(j,i) = NaN;
% pi_mat(j,i) = NaN;
% var_mat(j,i) = NaN;
solution_mat(j,i) = 0;
stab_mat(j,i) = 0;
else
% simdata0 = simulate(ms,'simul_regime',1,'simul_order',1,'simul_periods',1000);
% if isempty(simdata0)
% d_mat(j,i) = NaN;
% pi_mat(j,i) = NaN;
% stab_mat(j,i) = 0;
% solution_mat(j,i) = 0;
% var_mat(j,i) = NaN;
% else
% tempirf=irf(ms,'irf_periods',24,'irf_shock_sign',1);
% d_mat(j,i) = (tempirf.eps_G.B.data(4,1) - tempirf.eps_G.B.data(13,1)) > 0;
% pi_mat(j,i) = mean(simdata0.Pi.data);
% var_mat(j,i) = var(simdata0.Pi.data);
solution_mat(j,i) = ms.nsols;
stab_mat(j,i) = ms.is_stable_system;
% end
end
end
disp((j))
end
%figure(1)
%s = pcolor(stab_mat');
%s.LineStyle = '-';
%colormap(gray)
%teste = zeros(42,40);
%% Plot stability
figure(1)
set(1,'Color','w')
contourf(linspace(0,3,42),linspace(0.0,0.1,40),teste','LineStyle','-','LineWidth',0.2)
colormap(gray)
set(gca,'fontsize',10)
xlabel('Taylor Rule Parameter - $\phi_\pi$','interpreter','latex')
ylabel('Fiscal Parameter - $\delta_B$','interpreter','latex')
set(gca,'TickLabelInterpreter','latex')
%yticklabels([0.00 0.02 0.04 0.06 0.08 1.00])
set(gca,'fontsize',12)
line1 = '';
%line2 = 'Fixed Parameters';
%line2 = 'Exogenous Switching';
line2 = 'Endogenous Switching';
title(sprintf('\\begin{tabular}{c} %s %s %s \\end{tabular}',line1,'\\',line2),...
'interpreter','latex')
x0=1000;
y0=300;
width=350;
height=300;
set(1,'position',[x0,y0,width,height]);
%% Loop all selected parameters
for j = 1:grid_size
% 'c' stands for 'calibration'
c1 = struct('t_ss', t_ss_vec(j));
c2 = struct('delta_B_abc_1', delta_B_vec(j));
c3 = struct('rho_G', rho_G_vec(j));
c4 = struct('rho_T', rho_T_vec(j));
c5 = struct('kappa', kappa_vec(j));
c6 = struct('abc_tp_1_2', prob_vec(j));
% 'mc' stands for 'model with new calibration'
mc1 = set(m1,'parameters',c1);
mc2 = set(m1,'parameters',c2);
mc3 = set(m1,'parameters',c3);
mc4 = set(m1,'parameters',c4);
mc5 = set(m1,'parameters',c5);
mc6 = set(m1,'parameters',c6);
% Solve
ms1=solve(mc1,'solve_order',1,'solve_check_stability',false);
ms2=solve(mc2,'solve_order',1,'solve_check_stability',false);
ms3=solve(mc3,'solve_order',1,'solve_check_stability',false);
ms4=solve(mc4,'solve_order',1,'solve_check_stability',false);
ms5=solve(mc5,'solve_order',1,'solve_check_stability',false);
ms6=solve(mc6,'solve_order',1,'solve_check_stability',false);
% Has a solution? Is stable?
solution_mat(j,1) = ms1.nsols;
solution_mat(j,2) = ms2.nsols;
solution_mat(j,3) = ms3.nsols;
solution_mat(j,4) = ms4.nsols;
solution_mat(j,5) = ms5.nsols;
solution_mat(j,6) = ms6.nsols;
disp(j)
end
rise() is an undefined function.

Sign in to comment.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!