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
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Dyuman Joshi
2023-2-1
编辑:Dyuman Joshi
2023-2-2
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
更多回答(2 个)
Jan
2023-2-1
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
2023-2-13
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!