Replicating a matrix in matlab
1 次查看(过去 30 天)
显示 更早的评论
I have a matrix v=(1:2400,1). I want to replicate each element of v by the corresponding element in p=(1:2400). Here is the function I used to do the same.
for t=1:2400;
A(t,:)= repmat(v(t,1), 1, p(t));
end
But there is an error message which says ' Subscripted assignment dimension mismatch ' keeps coming. What can I do about this?
1 个评论
Muthu Annamalai
2013-6-17
Have you thought about using 'kron' and 'repmat' to rewrite your problem as a series of large matrix products? It requires some rearrangement on your part but it something that'll payoff nicely.
采纳的回答
Sean de Wolski
2013-6-17
dbstop if error
Then run your code. Look at each side of the parenthesis and I'm sure you'll see that:
size(A(t,:))
Is different than:
size(repmat(v(t,1),1,p(t)))
This makes sense too, p(t) cannot change size or you will see this error.
Perhaps you mean
A(t,1:p(t))?
i.e. fill the first p(t) elements with whatever repmat spits out.
更多回答(1 个)
Evan
2013-6-17
编辑:Evan
2013-6-17
Because the amount you're replicating each element of V by varies according to p, the resulting rows in A are not of the same size. As you create a regular matrix with variable row sizes, you're getting that error.
One way to get around this would be using a cell array instead of a normal array. Each cell would contain a row of your matrix A.
A = cell(2400,1);
for t=1:2400;
A{t,:} = repmat(v(t,1), 1, p(t));
end
Of course, there are reasons for and against doing this. Another option would be to pad the rows of your matrix A with zeros so that they're all the same size. But this might not be a good idea depending on what you're data in v is and what you're going to be doing with it.
Note: it looks like the code Sean posted above pads the matrix with zeros like I mentioned.
5 个评论
Evan
2013-6-17
You can change to matrix form but, for the same reasons as your error above, not all at once.
However, you can access the different cells of your cell array one at a time, so plotting the data using a for loop might work.
When you create your cell array, you'll get an array that's something like this for A:
[1 x p(1) double]
[1 x p(2) double]
[1 x p(3) double]
...
And so on. To access the contents of individual cells, call A{i}. So, if you needed to plot, you could do something like this:
for i = 1:length(A)
plot(x,A{i})
end
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!