How do I maintain my array size (or dimensions) when I run it through a nested for loop?

2 次查看(过去 30 天)
Hi All,
I have an array, 'data' (5x16x2), that I have shifted to the left (by 1 column) and zero-padded the right accordingly. However, when I run my variable through a nested for loop, my 3d array gets transformed to 2d (5x32). I'm facing some trouble trying to figure out how to maintain my array size as I run it through the nested for loop. I essentially want my 'dataShift' varible to be the same size as my 'data' variable (5x16x2).
My code looks like this:
%dummy data
for ii = 1:2
for i=1:16
data(:,i,ii)=i(:,:);
end
end
%constant variables
sink = 8;
layerIV = 7;
shift = abs(layerIV - sink);
%shift data
for ii = 1:2
for ch = 1:16
if sink > layerIV
dataShift = [data(:, shift+1:end), zeros(size(data,1),shift)];
end
end
end
I thought that perhaps the following might work:
dataShift(:,ch,ii) = [data(:, shift+1:end), zeros(size(data,1),shift)];
But I get the following error: "Unable to perform assignment because the size of the left side is 1-by-1 and the size of the right side is 1-by-32."
Would really appreciate any help.

采纳的回答

Dana
Dana 2020-9-1
You have 3-D arrays but are only using 2-D indexing (e.g., data(:, shift+1:end) only has two indices, even though data is a 3-D array). That's going to give you unexpected results. Also, your dummy data vector doesn't have 5 rows, just 1, which I'm assuming is a mistake.
I'm not entirely clear on exactly what you're after here, but does this give the desired result?
data = repmat(1:16,5,1,2); % better way to create your dummy data
%constant variables
sink = 8;
layerIV = 7;
shift = abs(layerIV - sink);
dataShift = [data(:,shift+1:end,:),zeros(size(data,1),shift,size(data,3))];

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by