How can I join columns of an array without overlapping elements?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Chunru
2022-9-20
编辑:Chunru
2022-9-20
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!