Filling in a 4d array

12 visualizzazioni (ultimi 30 giorni)
Charles Cummings
Charles Cummings il 20 Feb 2018
Commentato: Walter Roberson il 21 Feb 2018
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

Risposta accettata

Walter Roberson
Walter Roberson il 20 Feb 2018
earth = repmat(alien, 1, 1, 360, 6);

Più risposte (1)

Jan
Jan il 20 Feb 2018
Modificato: Jan il 20 Feb 2018
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 Commenti
Charles Cummings
Charles Cummings il 21 Feb 2018
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 il 21 Feb 2018
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.

Accedi per commentare.

Categorie

Scopri di più su Mathematics in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by