Replace rows of matrix with vector
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Jeremy
am 15 Jul. 2014
Kommentiert: Jeremy
am 15 Jul. 2014
So basically what I've done is create a function that allows me to replace a row within a matrix with a specified vector:
function [replacedM] = replace row(M,row,replace)
r=length(M);
for i=1:r
if M(i,:)==row
M(i,:)=replace;
end
end
replacedM=M;
end
Now, I have 2 matrices about 13260X3 in size. One is called prechanged, the other is called changed (where row m of 'changed' is the modified row m of 'prechanged.') My main matrix, 'main,' is about about 76000X3 in size. Multiple rows of 'main' have triplicate rows.
For example, 'main' looks something like:
1 2 3 1
2 8 1 0
1 2 3 1
2 0 8 2
3 0 8 8
1 2 3 1
0 0 1 2
Rows 1, 3 , and 6 all have the same values.
'prechange' would look something like:
0 0 1 2
1 2 3 1
2 0 8 2
2 8 1 0
3 0 8 8
'changed' would look something like:
0 0 2 4
2 4 6 2
4 0 4 4
4 4 2 0
6 0 4 4
I'm implementing the replacerow function on 'main' like this:
for j=1:length(pre)
main=replacerow(main,prechange(j,:),changed(j,:));
end
BUT it takes about 10 minutes (maybe because all main, prechange, and changed are extremely large matrices). Would anyone know if there is a way to shortening computational time? THANKS!
4 Kommentare
Akzeptierte Antwort
Joseph Cheng
am 15 Jul. 2014
Bearbeitet: Joseph Cheng
am 15 Jul. 2014
well here is a thing that you could do to speed it up.
function [M] = replace(M,row,replace)
[~,ind]=ismember(M,row,'rows');
ind = find(ind==1);
M(ind,:) = repmat(replace,length(ind),1);
end
and I tested it out using this
X = randi(10,76000,3);
prechange = randi(10,1000,3);
changed = randi(10,1000,3);
for i =1:length(prechange)
rowsdupe = randi(76000,1,randi(10000,1,1));
X(rowsdupe,:) = repmat(prechange(i,:),length(rowsdupe),1);
end
h=waitbar(0,'waiting')
tic
for j=1:length(prechange)
X=replace(X,prechange(j,:),changed(j,:));
waitbar(j/length(prechange),h,['performing step: ' num2str(j) '/' num2str(length(prechange))]);
end
close(h)
toc
elapsed time = 32.99 seconds.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Elementary Math finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!