- Negative indices as mentioned by Kye.
- Even if indices were positive integers, the way you redefine A makes it shrink at each iteration of the loop.
- Even if this is what you want to achieve, the static range coded in the FOR loop is likely not to be adequate as size(A,1) would change at each iteration.
- In your comment to Kye, you have i1=1:size(i,1) which is 1, so this example is probably not what you want to do.
This question is closed. Reopen it to edit or answer.
how do i vectorise given code?
1 view (last 30 days)
Hi Matlab Experts, Here is a numerical example of what I wish to vectorize:
for y = 1:10
for x = -10:10
if x > 0
A1= A(1+x:end, 5+y:end);
A2= A(1+x:end, 2+y:end);
A1= A(1:x+end, 5+y:end);
A2= A(1:x+end, 2+y:end);
A3 = A1-A2;
S = sum(A3(:).^3);
I wish to get rid of both for loops and wish to get the results S & A3 as a set of values in an array in fewer commands and faster mode as I need to use multiple times, I need to save every second that I can. Kindly help.
Cedric Wannaz on 26 Aug 2013
Edited: Cedric Wannaz on 26 Aug 2013
You should provide a numeric example, e.g. with a 4x4 array A, and show us a few steps of what you want to achieve. In your question/comments, the following issues prevent us to understand your goal:
Kye Taylor on 26 Aug 2013
Edited: Kye Taylor on 26 Aug 2013
I do not see how the example you provided will execute if A is any standard MATLAB data type.
In particular, if A is a MATLAB variable, such as a cell or a matrix, it can only be indexed using positive integers. In your example, when i is -5 (the first time through your for-loop), the expression A(i+2:end,:) is equivalent to A(-3:end,:), which is invalid since -3 is not a positive integer.
David Sanchez on 26 Aug 2013
If X is your matrix, here is how you get a 4x4 cell array out of your original matrix:
X = rand(20);
Y = mat2cell(X, repmat(5,[1 size(X,1)/5]), repmat(5,[1 size(X,2)/5]));
Adapt it to your needs.