Create one vector from several iterations in for loop

Hello, I am trying to split a vector into more pieces using a for loop. I have a vector, Lat, which contains latitude points. I wish to add more points in a linear fashion between the existing points in my Lat vector.
In order to do this, I am trying to use a for loop and the linspace operator as follows, splitting each interval in five new pieces.
for i = 1:length(Lat)-1
latitude(i) = linspace(Lat(i),Lat(i+1),5);
end
This does not work. How do I make the for loop understand that I wish to obtain a new vector containing all the points created using the linspace operator?

 Accepted Answer

Try this:
for i = 1:length(Lat)-1
latitude(i,:) = linspace(Lat(i),Lat(i+1),5);
end
latitude = reshape(latitude', 1, []);

6 Comments

Using this code I get the following error: Assignment has more non-singleton rhs dimensions than non-singleton subscripts.
Any idea how to fix this?
This works correctly for me:
Lat = 1:5;
for i = 1:length(Lat)-1
latitude(i,:) = linspace(Lat(i),Lat(i+1),5);
end
latitude = unique(reshape(latitude', 1, []))
latitude =
Columns 1 through 7
1 1.25 1.5 1.75 2 2.25 2.5
Columns 8 through 14
2.75 3 3.25 3.5 3.75 4 4.25
Columns 15 through 17
4.5 4.75 5
I added the unique call because the original code created duplicates of the start and end values in each iteration.
Thank you for your help! This works.
I am also trying to make the number here specified as 5 vary for each iteration based on how large the interval between the points in the Lat vector is. I have made a vector "splitperint" with i-1 values. However the following code does not work:
for i = 1:length(Lat)-1
latitude(i,:) = linspace(Lat(i),Lat(i+1),splitperint(i));
end
latitude = unique(reshape(latitude', 1, []));
Do you have any input on how I can make this work? Or is this simply not possible with the linspace operator?
That won’t work because the columns aren’t equal. A cell array will allow unequal-sized vectors.
I simulated your changed code using a cell array as:
Lat = 1:5;
for i = 1:length(Lat)-1
latitude{i} = linspace(Lat(i),Lat(i+1),5+i);
end
latitude = cell2mat(latitude);
latitude = unique(reshape(latitude', 1, []))
This works. Note the curly braces ‘{}’ indicating cell array addressing.
This works great! Thank you so much for you help!

Sign in to comment.

More Answers (1)

n = 5;
Latitude = [Lat(1);reshape(reshape(Lat(1:end-1),1,[])...
+ cumsum(ones(n,1)* diff(Lat(:)')/n),[],1)];

Categories

Asked:

on 11 Apr 2017

Commented:

on 13 Apr 2017

Community Treasure Hunt

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

Start Hunting!