Attempt to grow array along ambiguous dimension. it happens when N,M are smaller then the total of A,B. can I make my code work for any value of N,M? if so how would I do that
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Joshua
le 1 Fév 2023
Réponse apportée : Image Analyst
le 13 Fév 2023
N=5;
M=4;
A=[1 2 5 9 ; 23 23 874 243; 5 4 6 7; 5 09 23 31];
B=[7 8; 9 10; 12 11];
C=sort([A(:); B(:)]);
res=zeros(N,M);
res(1:length(C(:)))=C(1:end)
%the error I get is:
Attempt to grow array along ambiguous dimension.
Error on res(1:length(C(:)))=C(1:end)
0 commentaires
Réponse acceptée
Dyuman Joshi
le 1 Fév 2023
Modifié(e) : Dyuman Joshi
le 2 Fév 2023
The number of elements in C is greater than the total number of elements pre-allocated in res.
You can not put 22 elements in 20 place holders, where there is only one element per place holder; no matter the arrangement.
Nor can you grow it along any of the size/dimension to accomodate the extra elements, as stated in the error.
N=5; M=4;
A=[1 2 5 9 ; 23 23 874 243; 5 4 6 7; 5 09 23 31];
B=[7 8; 9 10; 12 11];
C=sort([A(:); B(:)]);
numel(C)
res=zeros(N,M);
numel(res)
"can I make my code work for any value of N,M? if so how would I do that"
Yes, your code will work for a values of N and M, iff N*M>=22
%%Examples -
%N=5, M=5, N*M=25 which is grater than 22
res1=zeros(5,5);
res1(1:numel(C))=C
%N=2,M=11, N*M=22 which is equalto 22
res2=zeros(2,11);
res2(1:numel(C))=C
Plus de réponses (2)
Jan
le 1 Fév 2023
Some simplifications:
- Use numel(C) instead of length(C(:)).
- C(1:end) is exactly the same as C.
The values to not matter the problem. A shorter version, which explains the problem:
res = zeros(5, 4);
C = ones(22, 1);
res(1:numel(C)) = C;
Matlab cannot guess, what the shape of res should be after this code and I can't also. There is no unique decision how to expand a [5x4] matrix to contan 22 elements.
I cannot suggest a solution, because it is unclear, what you want to achieve. This is the meaning of the error message.
Image Analyst
le 13 Fév 2023
Try this, which handles both cases: where res has more elements than C and where res has fewer elements than C:
rows = 5;
columns = 4;
A = [1 2 5 9 ; 23 23 874 243; 5 4 6 7; 5 09 23 31];
B = [7 8; 9 10; 12 11];
C = sort([A(:); B(:)]);
res = zeros(rows, columns);
if numel(res) < numel(C)
linearIndexes = 1 : numel(res);
else
linearIndexes = 1 : numel(C);
end
res(linearIndexes) = C(linearIndexes)
0 commentaires
Voir également
Catégories
En savoir plus sur Matrices and Arrays 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!