How can I join columns of an array without overlapping elements?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Emanoel Santos
le 20 Sep 2022
Commenté : Emanoel Santos
le 20 Sep 2022
So, I have a tri-diagonal (10x10) and would like to join some columns without overlapping the elements, that means columns 1,4, 7 and 10 can be joined without overlapping as well columns 2,5,8. All I have to do is put this elements together and all the other elements turn to 0. This is what I get, any suggestion? X is a random tri-diagonal matrix and Y the matrix with the joined columns.
clear all
x = [1 1 0 0 0 0 0 0 0 0; 2 3 4 0 0 0 0 0 0 0; 0 1 1 1 0 0 0 0 0 0; 0 0 1 1 1 0 0 0 0 0; ...
0 0 0 1 1 1 0 0 0 0; 0 0 0 0 2 4 3 0 0 0; 0 0 0 0 0 4 5 1 0 0; 0 0 0 0 0 0 1 1 1 0; ...
0 0 0 0 0 0 0 1 1 1; 0 0 0 0 0 0 0 0 1 1];
[nelem,ielem] = size (x);
y=zeros(nelem,nelem);
lin = 1;
col = 1;
j = 2;
if (x(lin,col) == 0 && x(lin,j) ~= 0 || (x(lin,col) ~= 0 && x(lin,j) == 0) || (x(lin,col)) == (x(lin,j)))
if(x(lin,col))~=0
y(lin,col)=x(lin,col);
elseif (x(lin,j))~=0
y(lin,col)= x(lin,j);
else
y(lin,col)=x(lin,col);
end
end
%COLUNAS 1 e 2
% for i = 2:nelem
i = 2;
while (i < nelem && j < nelem)
while (((x(i,col)==0)&&(x(i,j)~= 0))||((x(i,col)~=0)&&(x(i,j)==0))||((x(i,col)==0)&&(x(i,j)==0))&&j<nelem)
if (x(i,col)) ~= 0
y(i,col) = x(i,col);
else
y(i,col) = x(i,j);
end
if (i<nelem)
i=i+1;
elseif (i == nelem)
i = 1;
col = col +1;
j = j+1;
end
end
if (i < nelem && j < nelem)
y(:,col) = x(:,col);
i = 1;
j = j+1;
end
end
while(((x(i,col)) == 0 && (x(i,j)) ~= 0 || (x(i,col)) ~= 0 && (x(i,j)) == 0 ||(x(i,col)) == (x(i,j))) && i<nelem)
if (x(i,col) ==(x(i,j)))
y(i,col) = (x(i,col));
end
if((x(i,col))~=0 && (x(i,j)) == 0)
y(i,col)=x(i,col);
elseif ((x(i,col))==0 && (x(i,j)) ~= 0)
y(i,col)=x(i,j);
end
i=i+1;
end
if (x(i,col) ==(x(i,j)))
y(i,col) = (x(i,col));
end
if((x(i,col))~=0 && (x(i,j)) == 0)
y(i,col)=x(i,col);
elseif ((x(i,col))==0 && (x(i,j)) ~= 0)
y(i,col)=x(i,j);
end
6 commentaires
Réponse acceptée
Chunru
le 20 Sep 2022
Modifié(e) : Chunru
le 20 Sep 2022
Not sure if this is what you intend to do:
x = [1 1 0 0 0 0 0 0 0 0;
2 3 4 0 0 0 0 0 0 0;
0 1 1 1 0 0 0 0 0 0;
0 0 1 1 1 0 0 0 0 0;
0 0 0 1 1 1 0 0 0 0;
0 0 0 0 2 4 3 0 0 0;
0 0 0 0 0 4 5 1 0 0;
0 0 0 0 0 0 1 1 1 0;
0 0 0 0 0 0 0 1 1 1;
0 0 0 0 0 0 0 0 1 1];
y = zeros(size(x));
y(:, 1) = sum(x(:, [1 4 7 10]), 2);
y(:, 2) = sum(x(:, [2 5 8]), 2);
y(:, 3) = sum(x(:, [3 6 9]), 2);
y
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!