Effacer les filtres
Effacer les filtres

How to generate lines from coordinates?

11 vues (au cours des 30 derniers jours)
Nora Hora
Nora Hora le 29 Nov 2016
I have hundreds of pair of points. I would like to generates k lines with a loop and I would like to be able to save all of them later:
P1=(x1,y1) and P2=(x2,y2)
First 3 pairs of points of my data:
x1=[112 82 146];
x2=[549 292 574];
y1=[201 332 452];
y2=[470 93 59];
for k=1:length(x1)
line(k)=line([x1(k) x2(k)],[y1(k) y2(k)]);
end
However, I always recieve error for this and similar alternative solutions as well. For example: "Index exceeds matrix dimensions."
I don't understand the problem, I read other's questions but I didn't find a solution. Please help me, thank you for in advance!

Réponses (2)

Walter Roberson
Walter Roberson le 30 Nov 2016
You have
line(k)=line([x1(k) x2(k)],[y1(k) y2(k)]);
The first time you execute that, the variable line does not exist, and so MATLAB knows that the line on the right hand side refers to the key MATLAB graphics routine line() . It invokes that routine, which returns a graphics object handle. The left hand side tells MATLAB that it now needs to create a variable named line and assign the returned graphics handle into that variable.
The second time around the loop, the variable line already exists, and so on MATLAB knows that the line on the right hand side refers to the variable, and then tries to index that variable at the two dimensional index [x1(k) x2(k)] for the first dimension and [y1(k) y2(k)] for the second dimension. But the array line is only a scalar, so those indices are out of range of the size of the array.
Moral of the story: do not use sum or line or image as the name of a variable in MATLAB unless you intend to deliberately confuse yourself.

Image Analyst
Image Analyst le 30 Nov 2016
Don't use line as the name of a variable since it blows away the built-in line() function so you won't be able to draw lines anymore. Anyway drawing lines does not save the values. You already have the values, so to save them for later, as you asked, you can use several functions, for example save() or csvwrite() or others:
save(matFileName, 'x1', 'x2', 'y1', 'y2');

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by