Clear Filters
Clear Filters

Making an array using loop

2 views (last 30 days)
SWARNENDU PAL
SWARNENDU PAL on 30 Dec 2020
Edited: Paul Hoffrichter on 1 Jan 2021
A=[2;3;4;5;12;13;14;15;16;17;24;25;26;27;28;29;36;37;38;39;40;41;48;49;50;51;52;53;60;61;62;63;64;65;72;73;74;75;76;77;84;85;86;87;88;89;96;97;98;99;100;101;108;109;110;111;112;113;120;121];
How to make an array like A using loop. Thank you.
  3 Comments
SWARNENDU PAL
SWARNENDU PAL on 31 Dec 2020
that is the array. There is a pattern,plz notice carefully. If you provide me any other option that will be also helpful.Thank you.
Rik
Rik on 31 Dec 2020
Edited: Rik on 31 Dec 2020
Help us help you: explain the pattern and we might be able to help you write the code to create it.
The pattern is not obvious to me (nor, apperently, to Cris). It is also missing from the OEIS, which is generally an indication that the sequence is fairly obscure.

Sign in to comment.

Answers (1)

Paul Hoffrichter
Paul Hoffrichter on 31 Dec 2020
Edited: Paul Hoffrichter on 1 Jan 2021
Change ORIGINAL_POST to false to get slightly different result.
clearvars; clc; % remove previous debug runs
lenA = 60; % assumes you know the length of A
A = zeros(lenA,1); % pre-allocate A
maxSeqLen = 6;
ORIGINAL_POST = true;
if ORIGINAL_POST
start = 2;
seqLength = 4;
else
% rng(123);
start = randi(maxSeqLen,1);
seqLength = randi(maxSeqLen);
end
nominalSequence = 1:maxSeqLen;
skip = 7;
% Initialize
A(1:seqLength) = start:(start + seqLength - 1);
startLoc = seqLength + 1;
k = seqLength + 1;
while startLoc + maxSeqLen - 1 <= lenA
start = A(startLoc - 1) + skip;
A(startLoc:startLoc + maxSeqLen - 1) = start: start + maxSeqLen - 1;
start = start + maxSeqLen - 1 + skip;
startLoc = startLoc + maxSeqLen;
end
if startLoc <= lenA
maxSeqLen = lenA - startLoc + 1;
A(startLoc:startLoc + maxSeqLen - 1) = start: start + maxSeqLen - 1;
% if you cannot pre-allocate A, and have to enter values one at a time,
% then you can add elements like this: A = [A; new-value];
end
  2 Comments
Rik
Rik on 31 Dec 2020
You don't print anything to the command window, so what is the clc doing? And why are you suggesting clear all? mlint is clearly warning you not to use this.
Paul Hoffrichter
Paul Hoffrichter on 1 Jan 2021
Edited: Paul Hoffrichter on 1 Jan 2021
clc - used to remove previous debug runs where printing was done.
clear all - good point. Edited to say clearvars.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!