MATLAB Answers

create a vector without for

5 views (last 30 days)
The vector structure is like [a b c d e f g h i j]
a=1:10
b=1:10
...
j=1:5
vect=[]
I can use for a =1:10
for b=1:10
...
vect = [vect;a.b...j]
end
end
but it looks not elegant. Is there a better way to generate it?

  8 Comments

Show 5 older comments
Image Analyst
Image Analyst on 19 Jan 2020
So do you not want [a b c d e f g h i j] like you said, with a being a 10 element vector, b being another vector etc. (I gave my answer below assuming that.) David is assuming that a is really one element of your "a" (not the whole vector) and takes on every value in that a, so basically you have every possible permutation of all a values, etc.?
saihua lin
saihua lin on 19 Jan 2020
Thanks David. My question is a general question and no specific application. I can reduce it to [a b c d] for example.
a=1:10
b=1:10
c=1:3
d=1:5
Total array size is 10*10*3*5. So Yes, I'd like to have possible permutation. I can use for commands but it will need several for. If there're other more compact ways to generate these vectors, that would be good.
Stephen Cobeldick
Stephen Cobeldick on 19 Jan 2020
"I'd like to have possible permutation"
Then you should have asked about generating permutations: http://xyproblem.info/

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 19 Jan 2020
a=1:10;
b=1:10;
c=1:3;
d=1:5;
[A, B, C, D] = ndgrid(uint8(a), uint8(b), uint8(c), uint8(d)) ;
v = [A(:), B(:), C(:), D(:)] ;

  0 Comments

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 19 Jan 2020
Try
a = 1 : 10
b = 1 : 10
...
j = 1 : 5
outputVector = [a, b, c, d, e, f, g, h, i, j]

  0 Comments

Sign in to comment.

Sign in to answer this question.

Tags


Translated by