How can I have the numbers in one vector after a while loop?

2 views (last 30 days)
Ang Vas
Ang Vas on 10 Jun 2015
Edited: Stephen23 on 10 Jun 2015
Let say that I have a matrix A=[1 0 5 4; 2 0 5 4; 3 4 6 2]; and I am using the below code ( see my previews question Plot the numbers of a matrix as points (dots) in a plot) while any(A(:) > 0) [r,c] = find(A>0); X= randn; Y= randn; a=c+X b=r+Y A = A-1; end
it returns for a and b a =
1.4471
1.4471
1.4471
2.4471
3.4471
3.4471
3.4471
4.4471
4.4471
4.4471
b =
1.5364
2.5364
3.5364
3.5364
1.5364
2.5364
3.5364
1.5364
2.5364
3.5364
a =
0.6514
0.6514
1.6514
2.6514
2.6514
2.6514
3.6514
3.6514
3.6514
b =
3.1841
4.1841
4.1841
2.1841
3.1841
4.1841
2.1841
3.1841
4.1841
a =
1.2058
2.2058
3.2058
3.2058
3.2058
4.2058
4.2058
b =
3.1324
3.1324
1.1324
2.1324
3.1324
1.1324
2.1324
a =
1.4771
2.4771
2.4771
2.4771
3.4771
3.4771
b =
3.9398
1.9398
2.9398
3.9398
1.9398
2.9398
a =
1.6379
1.6379
1.6379
b =
0.2081
1.2081
2.2081
a =
3.6630
b =
3.5855
how can I have all the numbers of a and b in one vector respectively ?

Accepted Answer

Stephen23
Stephen23 on 10 Jun 2015
Edited: Stephen23 on 10 Jun 2015
Although it is slightly different in operation, you could try this:
A = [1 0 5 4; 2 0 5 4; 3 4 6 2];
N = sum(A(:));
X = randn(N,1)/12;
Y = randn(N,1)/12;
[R,C] = find(A>0);
B = A(A>0);
X = X + cell2mat(arrayfun(@(z,m)repmat(z,m,1),C,B,'UniformOutput',false));
Y = Y + cell2mat(arrayfun(@(z,m)repmat(z,m,1),R,B,'UniformOutput',false));
scatter(X,Y,[],randperm(N),'filled')
axis(gca,'ij')
colormap('winter')
which generates this figure:
The main differences from your code is that it generates all values at once (in the vectors X and Y) rather than within a loop, and it also uses a different random position for each point (rather than applying one random value to all points at each step of the while-loop). The code assumes that all values of A are positive integers or zero.
  4 Comments
Stephen23
Stephen23 on 10 Jun 2015
There is nothing wrong with being a beginner! Everyone here on this forum was once a beginner... it just takes time and lots of practice to learn a tool like MATLAB:
  • Read lots of examples of good MATLAB code
  • Learn to use the documentation.
  • Use this forum to learn some good techniques.
Good luck and have fun with MATLAB!

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!