Effacer les filtres
Effacer les filtres

How can I make a column appending columns which are of size of sum of other column?

3 vues (au cours des 30 derniers jours)
suppose i have three matrix of same length lat, lon and CG as
lat=[1 2 3 4 5];CG=[5 10 20 11 12];
i want to make like
lat=[lat(1).*ones(CG(1),1);lat(2).*ones(CG(2),1);lat(3).*ones(CG(3),1);lat(4).*ones(CG(4),1);lat(5).*ones(CG(5),1);];
how to do it with loop for large vectors?
i tried like this
n=length(CG)-1;
for i=1:n
kk=lat(i).*ones(CG(i),1);
kk1=[kk;lat(i+1).*ones(CG(i+1),1)]
end
it doesnot work.

Réponse acceptée

Stephen23
Stephen23 le 9 Jan 2019
Modifié(e) : Stephen23 le 9 Jan 2019
>> lat = [1,2,3,4,5];
>> CG = [5,10,20,11,12];
>> V = cell2mat(arrayfun(@(v,n)v*ones(n,1),lat(:),CG(:),'uni',0))
V =
1
1
1
1
1
2
2
2
2
2
2
2
2
2
2
3
3
3
3
3
3
3
3
3
3
3
3
3
3
3
3
3
3
3
3
4
4
4
4
4
4
4
4
4
4
4
5
5
5
5
5
5
5
5
5
5
5
5
Or, if you really want to use a loop:
N = numel(lat);
C = cell(N,1);
for k = 1:N
C{K} = lat(k).*ones(CG(k),1);
end
V = vertcat(C{:})

Plus de réponses (3)

TADA
TADA le 8 Jan 2019
lat=[1 2 3 4 5];
CG=[5 10 20 11 12];
output = repelem(lat', CG, 1);
  1 commentaire
Totanly
Totanly le 9 Jan 2019
??? Undefined function or method 'repelem' for input arguments of type 'double'.

Connectez-vous pour commenter.


Totanly
Totanly le 9 Jan 2019
lat2=lat(1).*ones(CG(1),1);
for k=2:length(CG)
lat2=[lat2;lat(k).*ones(CG(k),1)];
end
i made like this but its taking long time for large data.
  2 commentaires
TADA
TADA le 9 Jan 2019
Try Preallocating lat2 For Better Performance
TADA
TADA le 9 Jan 2019
try this:
lat=[1 2 3 4 5];
CG=[5 10 20 11 12];
windowIndices = [0 cumsum(CG)];
lat2=zeros(1,sum(CG));
for k=1:length(CG)
lat2(windowIndices(k)+1:windowIndices(k+1)) = repmat(lat(k), 1, CG(k));
end

Connectez-vous pour commenter.


Andrei Bobrov
Andrei Bobrov le 9 Jan 2019
J = cumsum(CG);
ii = zeros(J(end),1);
ii(J-CG+1) = 1;
out = lat(cumsum(ii));

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2009b

Community Treasure Hunt

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

Start Hunting!

Translated by