How do i create a loop for this expression?

2 Ansichten (letzte 30 Tage)
Burners
Burners am 1 Okt. 2012
Beantwortet: Nipun am 5 Jul. 2022
Taking the number of iterations to be 5
By using i=1:5
How do i use a loop "for" command to express this?
1 x 8 + 1
12 x 8 + 2
123 x 8 + 3
1234 x 8 + 4
12345 x 8 + 5
  2 Kommentare
Jan
Jan am 2 Okt. 2012
Bearbeitet: Jan am 2 Okt. 2012
Is this a homework assignment? Do you think you can deliver the soultion without cheating, if it has been posted here? What will you teacher think, when she reads her question here?
Please post what you have tried so far and explain which problems occurred.
@Forum members: Please think twice before answering homework questions. Give the pupils and students a chance to learn. The reputation of this forum suffers from homework cheating.
Imogen Loveday
Imogen Loveday am 11 Mär. 2015
pseudocode:
a = 0; for i = 1:5: a = 10a + i; f = 8a + i; print f;

Melden Sie sich an, um zu kommentieren.

Antworten (5)

Jan
Jan am 2 Okt. 2012
There is an elegant way without using strings: In the first iteratation the multiplicator is 1. In the 2nd iteration it is 10*1 + 2. In the 3rd it is 10*(10*1 + 2) + 3. This can be exploited by using a temporary variable and modify it in each iteration.

Wayne King
Wayne King am 1 Okt. 2012
Bearbeitet: Wayne King am 1 Okt. 2012
One way:
kk = '';
for ii = 1:5
kk = [kk num2str(ii)];
out = str2num(kk)*8+ii
end
Of course if you want to store the output in an array
kk = '';
for ii = 1:5
kk = [kk num2str(ii)];
out(ii) = str2num(kk)*8+ii;
end
Now out is a 1x5 vector with the output values

Azzi Abdelmalek
Azzi Abdelmalek am 1 Okt. 2012
Bearbeitet: Azzi Abdelmalek am 1 Okt. 2012
s='12345'
for k=1:length(s)
res(k)=str2num(s(1:k))*8+k
end
or without a loop
s='12345'
out=arrayfun(@(x) 8*str2num(s(1:x))+x,1:5)

Maneet Kaur Bagga
Maneet Kaur Bagga am 5 Jul. 2022
As per my understanding you want to use for loop for 5 iterations and display the result of the expression.
You can use a variable i with initial value 1 and a variable num with initial value 0
At every iteration the value of num will be (num*10 + i) and result will be (num*8 + i) and then you can print the result. You can refer the below code. Hope it helps.
num=0
num = 0
for(i=1:5)
num = num*10 + i
result = (num)*8 + i
end
num = 1
result = 9
num = 12
result = 98
num = 123
result = 987
num = 1234
result = 9876
num = 12345
result = 98765

Nipun
Nipun am 5 Jul. 2022
Hi Burners,
Hope this works for you!
str = "0";
for i = 1:5
str = string(str2double(str)*10+(i));
ans = (str2double(str))*8+i
end

Kategorien

Mehr zu Loops and Conditional Statements 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!

Translated by