How can I change the 1_D array to the 2_D in specific case?

Hello everyone pleas How can I rewrite the 1_D array(X) into 2_D array(New_X)?
For example:
X=[0 1 0 2 3 0 4 5 6 0 7 8 9 10 0];
into
New_X(i,j)=[0 1 2 4 7
1 0 3 5 8
2 3 0 6 9
4 5 6 0 10
7 8 9 10 0];

 Réponse acceptée

DGM
DGM le 3 Juin 2021
Modifié(e) : DGM le 3 Juin 2021
It would probably be easier to build the array without starting from the vector, but I imagine it's a requirement. It could be done simply enough with a loop, but I don't feel like loops at the moment.
X=[0 1 0 2 3 0 4 5 6 0 7 8 9 10 0];
n = sqrt(2*numel(X) + 1/4) - 1/2; % find output array size
C = mat2cell(X,1,1:n); % split the vector into chunks
f = @(x) [x zeros(1,n-numel(x))]; % pad chunks to equal length
C = cell2mat(cellfun(f,C,'uniformoutput',false).'); % rearrange
C = C + C.' % combine
C = 5×5
0 1 2 4 7 1 0 3 5 8 2 3 0 6 9 4 5 6 0 10 7 8 9 10 0

4 commentaires

That was amazing thank you so much. i did it with two for loops and counter but the results was incorrect.
We can allso useing (find function) to find output array size, such as :
n=numel(find(X==0));%find output array size
Actually, yeah that works too so long as the diagonal is a unique constant value.
In the case where there are other zeros in the pattern, or if the diagonal is not zero-valued, my method for finding the array size still works (so long as X represents the same triangular portion of the matrix). However, the latter case has an extra complication in assembling the final output. Consider:
% diagonal elements are random or unknown nonzero pattern
X = [-8 1 4 2 3 -1 4 5 6 15 7 8 9 10 -20];
% all this is the same
n = sqrt(2*numel(X) + 1/4) - 1/2;
C = mat2cell(X,1,1:n);
f = @(x) [x zeros(1,n-numel(x))];
C = cell2mat(cellfun(f,C,'uniformoutput',false).');
% but this modification keeps from doubling the diagonal
% this isn't necessary if the diagonal is zero,
% but it would still work if it were.
C = tril(C,-1) + C.'
C = 5×5
-8 1 2 4 7 1 4 3 5 8 2 3 -1 6 9 4 5 6 15 10 7 8 9 10 -20
Very good example, you explained it very well.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Sparse Matrices dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by