Filling in a 4d array

3 ビュー (過去 30 日間)
Charles Cummings
Charles Cummings 2018 年 2 月 20 日
コメント済み: Walter Roberson 2018 年 2 月 21 日
Hey everyone!
Got a 4d array I am trying to populate. Preallocated the array as a (221x2x360x6) array of zeros.
Say my array name is earth. earth(:,:,1:360,1:6)=[alien(:,1),alien(:,2)]
Where alien is a 221x2 array. I am getting back an error saying the assignment has fewer non-singleton rhs dimensions than non-singleton subscripts. I've tried this a few different ways. Could I fill in each row individually with a loop?
Thanks fellow terrestrials

採用された回答

Walter Roberson
Walter Roberson 2018 年 2 月 20 日
earth = repmat(alien, 1, 1, 360, 6);

その他の回答 (1 件)

Jan
Jan 2018 年 2 月 20 日
編集済み: Jan 2018 年 2 月 20 日
earth = zeros(221, 2, 360, 6);
alien = rand(221, 2);
size(earth(:, :, 1:360, 1:6))
size([alien(:,1), alien(:,2)]) % Or easier and faster: size(alien(:, 1:2))
You see, the sizes differ. But you can use repmat:
earth(:, :, 1:360, 1:6) = repmat(alien(:, 1:2), 1, 1, 360, 6);
Or as simplification:
earth(:, :, :, :) = repmat(alien(:, 1:2), 1, 1, 360, 6);
because earth was pre-allocated correctly already. But then earth is overwritten completely and the pre-allocation was useless. Simply omit it, because pre-allocation is required to avoid the iterative growing of an array, but your array is created at once. Then a pre-allocation is a waste of time only.
earth = repmat(alien(:, 1:2), 1, 1, 360, 6);
  2 件のコメント
Charles Cummings
Charles Cummings 2018 年 2 月 21 日
Why do I use 1,1 for the first two dimensions of repmat? I know that is what corrects the error i was getting,'Assignment has fewer non-singleton dimensions than non-singleton subscripts,' but do not know why.
Walter Roberson
Walter Roberson 2018 年 2 月 21 日
The numbers give the number of times the data needs to be replicated in that dimension. Your source data is already the correct size in the first and second dimension, so you use a factor of 1 for those two. Your source data is too small by a factor of 360 in the third dimension -- you have to take it from being size 1 to size 360 -- so you use 360 there. And so on. The number should be the ratio between the existing size and the desired size, in each dimension.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMATLAB Mobile Fundamentals についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by