I have matrix:
x=[0 0 0;5 8 0; 7 6 0]
I want matrix:
m=[0 0 0;5 8 0;7 6 0; 0 0 8;5 8 8;7 6 8; 0 0 16;5 8 16;7 6 16]
I want that the third column of matrix x
gets multiplied each time by 8 while other two columns remain same. I want this to continue until the value in third column reaches 72.
How can I do it with bsxfun
or any other way?
Assuming the following two assumptions, you could try an approach listed thereafter -
adding
rather than multiplying
.column-3
to reach at least 72
.Approach #1 [With bsxfun
]
stopn = 72; %// stop adding till this number
add_factor = 8; %// Add factor to be added at each iteration to get to 72
ntimes = ceil(max((stopn - x(:,3))/add_factor)) %// no. of iterations needed
%// Get the starting 2d version of matrix to be added to x iteratively
x_add_2d = zeros(size(x)); %//
x_add_2d(:,3) = add_factor;
%// Get the complete version of matrix to be added (in 3d), then add to x
x_add_3d = bsxfun(@plus,x,bsxfun(@times,x_add_2d,permute([0:ntimes],[1 3 2])))
%// Concatenate along rows to form a 2D array as the final output
out = reshape(permute(x_add_3d,[1 3 2]),size(x_add_3d,1)*(ntimes+1),[])
Approach #2 [With repmat
]
stopn = 72; %// stop adding till this number
add_factor = 8; %// Add factor to be added at each iteration to get to 72
ntimes = ceil(max((stopn - x(:,3))/add_factor)); %// no. of iterations needed
out = repmat(x,[ntimes+1 1]) %// replicated version of x
add_col3 = repmat([0:8:ntimes*8],size(x,1),1) %// column-3 values to be added
out(:,3) = out(:,3) + add_col3(:) %// add those for the final output
Sample run -
x =
52 43 57
41 40 48
41 49 50
out =
52 43 57
41 40 48
41 49 50
52 43 65
41 40 56
41 49 58
52 43 73
41 40 64
41 49 66
52 43 81
41 40 72
41 49 74