Replicating a matrix in matlab
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Muthu Annamalai
el 17 de Jun. de 2013
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.
Respuesta aceptada
Sean de Wolski
el 17 de Jun. de 2013
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.
Más respuestas (1)
Evan
el 17 de Jun. de 2013
Editada: Evan
el 17 de Jun. de 2013
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 comentarios
Evan
el 17 de Jun. de 2013
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
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!