Modifying the elements of matrix from indices (MATLAB)
1 次查看(过去 30 天)
显示 更早的评论
I have a number of elements m for example m=4. And the matrix is square of dimensions m*m
P =
1 2 3 4
2 3 4 3
3 4 3 2
4 3 2 1
using the following program to replace the indices 1, 2, 3...m with its sub-matrices:
m=input('Initialize a number of elements'); % Number of elements in the matrix
P=hankel(1:m,m:-1:1);
% Initialisation of sub-matrices of dimensions (m-1 x m-1)
a=zeros(m-1,m-1,m-2);
a(:,:,1)=eye(m-1); % First sub-matrix is always an identity matrix with indice = 1 in P
for k=2:m-1
a(:,:,k)=circshift(a(:,:,k-1),1,2 ); % Other sub-matrices of indice = 2 to m-1
end
a(:,:,m) = zeros(m-1); % Final sub-matrix of indice = m (always null)
% Replacing the sub-matrices of indices 1,2,...m in P
N = zeros(m*(m-1));
a = num2cell(a,[1 2]);
for ii = 1:m
for jj = 1:m
N((m-1)*(ii-1)+1:(m-1)*ii,(m-1)*(jj-1)+1:(m-1)*jj) = a{P(ii,jj)};
end
end
I added this part of program to find always two indices of sum=m. For example in the case of m=4 the indices are 1 and 3 to find 1+3=m
indice=0;
while sum(indice)~=m
indice=randi([1,m-1],[1,2]);
end
So the indice 2 is not used here. We use just 1, 3 and m.
I need to add a part in the prgram that replace all the sub-matrices of indices that are not used (in this example indice 2) with null matrices in the matrix N. How can I do that please.
4 个评论
Voss
2022-3-11
Are you saying that you have some code to prevent repeated indices, e.g., [2 2], or that you still need to write such code?
Also, what do you mean by null matrices? A matrix of the appropriate size which is all NaNs?
采纳的回答
Voss
2022-3-11
Here is a function you can use to get a pair of random indices that sum to m but are never [m/2 m/2]:
function idx = get_random_index(m)
if mod(m,2) % m is odd: no chance of getting m/2 from randi()
idx = randi([1 m-1]); % just use the result from randi()
else % m is even: could get m/2 from randi(), so use randi()
% to get an integer between 1 and m-2, then increase it
% by 1 if it is >= m/2, so you end up with a random index
% between 1 and m-1 excluding m/2
% e.g., for m == 4:
% randi() returns 1: idx = 1
% randi() returns 2: idx = 3
% e.g., for m == 6:
% randi() returns 1: idx = 1
% randi() returns 2: idx = 2
% randi() returns 3: idx = 4
% randi() returns 4: idx = 5
idx = randi([1 m-2]);
if idx >= m/2
idx = idx+1;
end
end
idx = [idx m-idx]; % return the 2 indices whose sum is m
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!