Creating a loop for repeated vector values
1 次查看(过去 30 天)
显示 更早的评论
Hi,
I am attempting to setup a massive vector made up of Current values for a battery model. Before this piece of code I have included, the PosAccelReqCurrent already has 15 values. Is it possible to make a loop to repeat the values below for x amount of times rather than just copy and pasting it x times? It would make my code a lot of more efficient rather than having thousands of lines of the same code.
As further context, this code is to create many repeated current cycles to test battery degredation over time. Apologies if I have not added enough explanation.
Thank you.
%%%%%%%%%%%%%%%
maxPARC = length(PosAccelReqCurrent);
for x=1:6500
PosAccelReqCurrent(maxPARC+x)=PosAccelReqCurrent(15);
end
for x=1:6500
ActVel(maxPARC+x)=ActVel(15);
end
maxPARC = length(PosAccelReqCurrent);
for x=1:100
PosAccelReqCurrent(maxPARC+x)=0;
end
for x=1:100
ActVel(maxPARC+x)=ActVel(15);
end
maxPARC = length(PosAccelReqCurrent);
for x=1:3470
PosAccelReqCurrent(maxPARC+x)=15;
end
for x=1:3470
ActVel(maxPARC+x)=0;
end
%%%%%%%%%%%%%%%%%%%%
0 个评论
采纳的回答
Voss
2024-4-25
编辑:Voss
2024-4-25
No loops necessary.
If those are row vectors, then:
newPARCdata = [PosAccelReqCurrent(15)*ones(1,6500) zeros(1,100) 15*ones(1,3470)];
newAVdata = [ActVel(15)*ones(1,6600) zeros(1,3470)];
PosAccelReqCurrent = [PosAccelReqCurrent repmat(newPARCdata,1,x)];
ActVel = [ActVel repmat(newAVdata,1,x)];
If they are column vectors, then:
newPARCdata = [PosAccelReqCurrent(15)*ones(6500,1); zeros(100,1); 15*ones(3470,1)];
newAVdata = [ActVel(15)*ones(6600,1); zeros(3470,1)];
PosAccelReqCurrent = [PosAccelReqCurrent; repmat(newPARCdata,x,1)];
ActVel = [ActVel; repmat(newAVdata,x,1)];
1 个评论
Voss
2024-4-25
Here's a way that works whether they are row or column vectors:
newPARCdata = [PosAccelReqCurrent(15)*ones(1,6500) zeros(1,100) 15*ones(1,3470)];
newAVdata = [ActVel(15)*ones(1,6600) zeros(1,3470)];
PosAccelReqCurrent(end+(1:numel(newPARCdata)*x)) = repmat(newPARCdata,1,x);
ActVel(end+(1:numel(newAVdata)*x)) = repmat(newAVdata,1,x);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Naming Conventions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!