Matrix with repetitions of a vector

2 次查看(过去 30 天)
M = [1:8];
A = repmat(M,1,4)
I have these two vector. I need to create a 6x32 matrix with repetitions of the vector A, different to the original.
for i = 2:6
A(i,:) = A(randperm(length(A)))
end
I tried this loop, but I need to make sure some conditions:
First matrix, rows have to have different starting number.
Second matrix, it can happen only once that a number is followed by the same number
Third matrix, numbers 5 and 6 cannot be followed by numbers 7 and 8 respectively

回答(2 个)

dpb
dpb 2019-5-28
A=repmat(M,6,4);
is what you say literally, but I don't follow what you mean by "with repetitions of the vector A, different to the original". What is to be "different to the original" and how so?
  2 个评论
Ana Maria Alzate
Ana Maria Alzate 2019-5-28
编辑:Image Analyst 2019-5-28
A = repmat(M,6,4)
With this function I was getting repetition of the vector, and I need it to be sorted differently in each row.
A(i,:) = A(randperm(length(A)))
I found this function and it is working, except there are the other conditions, like rows cannot start with the same number, etc.
Image Analyst
Image Analyst 2019-5-28
Sounds like homework. Is it? Is so, we need to know so that we don't just give you the complete solution which might get you into trouble.
Do you need help setting up a "while" loop?

请先登录,再进行评论。


Jan
Jan 2019-5-28
This sounds like a homework question, but you did not mention thuis explicitly. The solution is easy, but I do not want to solve your homework.
M = 1:8; % No square brackets needed, because 1:8 is a vector already
A = repmat(M, 1, 4);
ready = false;
while ~ready
Result = zeros(6, 32);
Result(1, :) = A;
for i = 2:6
Result(i,:) = A(randperm(numel(A)));
end
ready = <expression to check the wanted condition>
end
You can use this brute force approach. Fill in a test, if the wanted condition is met.
  • "rows have to have different starting number": This means, that unique(A(:, 1)) must reply 6 elements.
  • "it can happen only once that a number is followed by the same number": Use diff(A, 1, 2). Then sum helps to count the zeros. By the way: In which direction is "follow" defined here?
  • "numbers 5 and 6 cannot be followed by numbers 7 and 8 respectively": Again "follow" is not clear. Use strfind to search for [5,7] and [6,8]. strfind works on row vectors also, but inspite of its name it accepts numerical input also.
Please try to implement this and ask a specific question on demand.

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by