Effacer les filtres
Effacer les filtres

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)
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)

Réponse acceptée

Dyuman Joshi
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)
ans = 22
res=zeros(N,M);
numel(res)
ans = 20
"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
res1 = 5×5
1 5 9 12 243 2 6 9 23 874 4 7 9 23 0 5 7 10 23 0 5 8 11 31 0
%N=2,M=11, N*M=22 which is equalto 22
res2=zeros(2,11);
res2(1:numel(C))=C
res2 = 2×11
1 4 5 6 7 9 9 11 23 23 243 2 5 5 7 8 9 10 12 23 31 874

Plus de réponses (2)

Jan
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;
Attempt to grow array along ambiguous dimension.
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
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)

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Tags

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by