Basically I have been trying to come up with a 2D array loop in Matlab. It will create a 5 column array for example that starts of with full 100's and removes the 5th column by an interval of 10 until it hits zero and then moves onto the 4th column and starts at 90, then the 5th column (starting at 90) goes down to zero. This repeats until all the numbers have become zero. Im looking for some sort of loop that creates something like this:
100 100 100 100 90
100 100 100 100 80
100 100 100 100 70 .....
100 100 100 90 90 .....
100 100 100 90 80
100 0 0 0 0 ....
0 0 0 0 0
But I am really struggling to come up with a simple loop for it.
If anyone has an ideas on how to create this I would really appreciate it.
CodePudding user response:
The following should get you started. Its a very nice application possibility of the Kronecker Tensor Product to get a fully vectorized solution without loop.
Parameters:
step = 20;
nrows = 3;
nsteps = 5;
As one-liner:
A = cumsum(kron(fliplr(eye(nrows)),step*ones(nsteps,1)),1,'reverse');
with explanation:
basepattern = fliplr(eye(nrows)); % general matrix design
subpattern = step*ones(nsteps,1); % pattern to repeat
a = kron(basepattern, subpattern); % kronecker delta to repeat apttern
A = cumsum(a,1,'reverse'); % cumulative sum upwards
% optional: filter out lines:
A(1:5:end,:) = [];
% optional: pad zeros at the end
A(end 1,:) = 0;
Result
A =
100 100 80
100 100 60
100 100 40
100 100 20
100 80 0
100 60 0
100 40 0
100 20 0
80 0 0
60 0 0
40 0 0
20 0 0
0 0 0
CodePudding user response:
Here's a simple loop-approach that does what you want. You have to make minor adjustments for it to work with the steps you want, but that should be simple:
c = 4; % number of columns
n = 3; % starting number
x = zeros(n*c 1, c); % Initial matrix of zeros
for ii = 1:c
last_idx(ii) = ((n*c 1)-n)-(ii-1)*n;
x(1:last_idx(ii),ii) = n;
x(last_idx(ii) [1:n-1], ii) = [n-1:-1:1];
end
x =
3 3 3 3
3 3 3 2
3 3 3 1
3 3 3 0
3 3 2 0
3 3 1 0
3 3 0 0
3 2 0 0
3 1 0 0
3 0 0 0
2 0 0 0
1 0 0 0
0 0 0 0