- 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.
how do i vectorise given code?
1 ビュー (過去 30 日間)
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.
回答 (3 件)
Cedric Wannaz 2013 年 8 月 26 日
編集済み: Cedric Wannaz 2013 年 8 月 26 日
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 2013 年 8 月 26 日
編集済み: Kye Taylor 2013 年 8 月 26 日
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 2013 年 8 月 26 日
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.