Creating a loop for repeated vector values

조회 수: 7 (최근 30일)
Topperanium
Topperanium 2024년 4월 25일
편집: Voss 2024년 4월 25일
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
%%%%%%%%%%%%%%%%%%%%

채택된 답변

Voss
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
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 CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by