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 回表示 (過去 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!