Asked by Dylan George
on 9 Jan 2019

Hi everyone, anyone know how to make a loop, or automate this somehow, got 30+ lines of this! Thanks

xdata1 = data([extendedX1coordinates(:,1):X2coordinates(:,1)],[Y1coordinates(:,1):Y2coordinates(:,1)],:) ;

xdata2 = data([extendedX1coordinates(:,2):X2coordinates(:,2)],[Y1coordinates(:,2):Y2coordinates(:,2)],:) ;

xdata3 = data([extendedX1coordinates(:,3):X2coordinates(:,3)],[Y1coordinates(:,3):Y2coordinates(:,3)],:) ;

xdata4 = data([extendedX1coordinates(:,4):X2coordinates(:,4)],[Y1coordinates(:,4):Y2coordinates(:,4)],:) ;

xdata5 = data([extendedX1coordinates(:,5):X2coordinates(:,5)],[Y1coordinates(:,5):Y2coordinates(:,5)],:) ;

xdata6 = data([extendedX1coordinates(:,6):X2coordinates(:,6)],[Y1coordinates(:,6):Y2coordinates(:,6)],:) ;

Answer by madhan ravi
on 9 Jan 2019

Don't think of naming variables dynamically ( https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval )use cell instead:

xdata=cell(1,size(extendedXicoordinates,2)); % preallocate

for i = 1:size(extendedXicoordinates,2)

xdata{i} = data(extendedXicoordinates(:,i):X2coordinates(:,i),Yicoordinates(:,i):Y2coordinates(:,i),:) ;

end

celldisp(xdata)

Dylan George
on 9 Jan 2019

Sign in to comment.

Answer by Matt Tearle
on 9 Jan 2019

It might help to know a bit more about what you're actually trying to do. Given that you're indexing with (:,k), it seems that the variables XXXcoordinates are matrices...? But then you're extracting columns, so column:column would be weird and may not be doing what you want. So maybe those variables are vectors?

Then what are you going to do with the result? As Madhan points out, you don't want 30 uniquely named variables in your workspace. What's the end goal here?

Dylan George
on 9 Jan 2019

Matt Tearle
on 16 Jan 2019

OK, if the coordinates are row vector (1-by-34), then data(x1(:,i):x2(:,i)) is valid, although I'd still prefer to write it as data(x1(i):x2(i)) for clarity. I find the use of row, column indexing with the colon confusing when the result is a single index value.

But now I don't see why Madhan's code isn't doing what you want.

xdata{i} = data(x1(i):x2(i),y1(i):y2(i),:)

The ith cell of xdata will be a portion of data, with the rows and columns extracted being defined by x1, x2, y1, and y2. If the size of xdata{i} isn't what you'd expect, you'll need to look at the values of x1(i), x2(i), y1(i), and y2(i).

One thing to be wary of: if you think of x and y in our normal mathematical arrangement (x horizontal, y vertical), then as indices x would correspond to columns and y to rows. (So data(y1(i):y(2),x1(i):x2(i),:).)

Sign in to comment.

Answer by Dylan George
on 9 Jan 2019

thanks for your help so far madhan.! It only gives me 3x4x100 though :/

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.