How can I create a matrix from the values of a For loop?

2 views (last 30 days)
I want to creat a matrix of 2 columns and the obtained rows after doing a for and if loops. I only want to create the matrix when the value of x2 pass the if condition. In this way, I want to get the x2 values on the first column and the b values on the second one. And not overwrite in the before value. I dont know how to do it. I would appreciate your help.
This is my code:
b=
0
0,510000000000000
1,02000000000000
1,53000000000000
2,03000000000000
2,54000000000000
-0,510000000000000
-1,02000000000000
-1,53000000000000
-2,54000000000000
-2,03000000000000
-3,04000000000000
alpha=10;
m=tand(alpha);
c=-40:1:3; %x-en mobitu bidana
y0=-3.5;
y1=3.5;
k=1;
h=1;
x2=zeros(size(CoordX));
matrix=zeros(size(CoordX),2);
for i=1:1:length(c)
n=y0-m*c(i);
x1=(y1-n)/m;
plot([c(i) x1],[y0 y1],'r');
for j=1:1:length(b)
x2(k)=(b(j)-n)/m;
scatter(x2(k),b(j),'g');
if x2(k)>posX_min && x2(k)<posX_max
matrix(:,h)=[x2(k) b(j)];
j=j+1;
k=k+1;
h=h+1;
end
end
i=i+1;
end

Answers (1)

Nut
Nut on 2 Mar 2017
Edited: Nut on 2 Mar 2017
Hi,
I'm not sure, but I think you can try this (I refer to the first version of code that you wrote):
matrix = [];
for j=1:1:length(b)
x2(k)=(b(j)-n)/m;
scatter(x2(k),b(j),'g');
if x2(k)>posX_min && x2(k)<posX_max
matrix(size(matrix,1)+1,:) = [x2(k) b(j)];
k=k+1;
end
j=j+1;
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!