Generate expandable code for a particular matrix

I have devleoped the code to build a matrix of combinations of 1 and 2 in the diagonal (see below). I would like to have to code to be flexible so that is would do this for a matrix of size N instead of just 3.
A = zeros(3);
for i = 1:2
for j = 1:2
for k = 1:2
A(1,1) = i;
A(2,2) = j;
A(3,3) = k;
A
end
end
end

Réponses (1)

Voss
Voss le 30 Avr 2022
N = 5;
% The idea is to count up in binary from 0 to 2^N-1,
% but use 1s and 2s instead of 0s and 1s, then place
% the elements along the diagonal of A. (This
% generates the various diagonals of A in the same
% order as your code does.)
A = zeros(N);
for ii = 0:2^N-1
A(1:N+1:end) = dec2bin(ii,N)-'0'+1
end
% dec2bin(ii,N) ........ convert ii to a binary char vector N bits long, e.g.,
% dec2bin(6,3) is '110', dec2bin(14,5) is '01110'
% -'0' .... then subtract the character '0' to get a vector of
% doubles, with 0 where the char vector had '0' and 1
% where it had '1'
% +1 .. add 1 to make it 1 where the char vector was '0'
% and 2 where it was '1'
% A(1:N+1:end) = ...................... store the result along the diagonal of A (linear
% index 1:N+1:end)

Catégories

En savoir plus sur Matrices and Arrays 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