MATLAB Answers

I need help with my While Loop!

2 views (last 30 days)
Uma Dixit
Uma Dixit on 23 Feb 2020
Commented: darova on 26 Feb 2020
I have an original array (3D) called 'pixelArray' that I eventually need to crop 3 different ways. So I have 3 different sets of x1,x2,y1,y2 numbers that crop the original array in different ways.
I currently have it set up like this:
x1 = [52, 52, 52];
x2 = [480, 480, 480];
y1 = [4, 1, 205] ;
y2 = [392, 205, 392];
n = 1;
while n < 3
%crop rows
pixelArray(1:y1(n),:,:)=[];
pixelArray(y2(n):end,:,:) = [];
%crop columns
pixelArray(:,1:x1(n),:)=[];
pixelArray(:,x2(n):end,:)=[];
n =n+1;
end
But I want to save each iteration's new pixelArray as its own matrix. What is the best way to go about doing this?

  3 Comments

darova
darova on 24 Feb 2020
Remember that after first removing [] size is changing:
Uma Dixit
Uma Dixit on 26 Feb 2020
Oh, very good point. How do you suggest I make sure the original pixelArray matrix stays intact in its dimensions?
darova
darova on 26 Feb 2020
Remove elements from the end?
>> a = 1:10
a =
Columns 1 through 9
1 2 3 4 5 6 7 8 9
Column 10
10
>> a(7:9) = []
a =
1 2 3 4 5 6 10
>> a(1:3) = []
a =
4 5 6 10

Sign in to comment.

Accepted Answer

Jakob B. Nielsen
Jakob B. Nielsen on 24 Feb 2020
Edited: Jakob B. Nielsen on 24 Feb 2020
Index them! Either as a structure, or an array with a 4th dimension. I personally favour structures, since 4D data makes my head hurt ;) dot indexing is great for looping results.
Also note that you will only get 2 runs of your loop, as after the 2nd run n will equal 3, and your loop terminates before running a 3rd time since the condition is less than 3. Either make the condition less than or equal to 3, or you can use a for loop instead, as your while loop is essentially a for loop where you do the counting yourself - something you dont need to do in this case.
for n=1:3
%crop rows
pixelArray(1:y1(n),:,:)=[];
pixelArray(y2(n):end,:,:) = [];
%crop columns
pixelArray(:,1:x1(n),:)=[];
pixelArray(:,x2(n):end,:)=[];
Crops(n).pixelArray=pixelArray;
end

  0 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!