Increment different rates in same for-loop

1 Ansicht (letzte 30 Tage)
Niclas Madsen
Niclas Madsen am 1 Okt. 2018
Bearbeitet: Stephen23 am 2 Okt. 2018

I have 3 different size matrix that are all supposed to be used in the same calculations. The issue I have is that matrix 1 is 8x1, matrix 2 is 4x1 and matrix 3 is 2x1. The increment rates that I need for M1, M2 and M3 are i, j and k respectively.

I need to for instance multiply M1(1,1) with M2(1,1) and M3(1,1) which is easy, but the next step would be

M1(2,1) * M2(1,1) * M3(1,1)
M1(3,1) * M2(2,1) * M3(1,1)
...
M1(8,1) * M2(4,1) * M3(2,1)

So for every iteration of the loop i increments by 1, j increments by half of i and k increments by a quater.

I've attempted to do it like so

for i = 1:8
   j = round(i/2);
   k = round(i/4);
   M1(i,1) * M2(j,1) * M3(k,1)
end

However, k assumes the values of [0 1 1 1 1 2 2 2] which is almost correct. How can I correct my small offset in my k increments - or better yet, is there a smarter way around this problem?

Thanks,

Niclas

  1 Kommentar
ANKUR KUMAR
ANKUR KUMAR am 1 Okt. 2018
You value of k is [0,1,1,....]. While running the loop, it will throw this error,
Subscript indices must either be
real positive integers or logicals.
,for sure because you are using M3(k,1) later in the program, which never be possible in case of k=0;

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Niclas Madsen
Niclas Madsen am 2 Okt. 2018
I've solved the issue using this format:
iter = [1 2 3 4 5 6 7 8; 1 1 2 2 3 3 4 4; 1 1 1 1 2 2 2 2];
for i = 1:8
j = iter(1,i)
k = iter(2,i)
l = iter(3,i)
M4(i) = M1(j,1) * M2(k,1) * M3(l,1)
end

Weitere Antworten (1)

Stephen23
Stephen23 am 2 Okt. 2018
Bearbeitet: Stephen23 am 2 Okt. 2018
Method one: a loop:
N = 8;
Z = nan(1,N); % preallocate
for k = 1:N
Z(k) = M1(k) * M2(ceil(k/2)) * M3(ceil(k/4));
end
Method two: without a loop using indexing:
X = 1:numel(M1);
Z = M1 .* M2(ceil(X/2)) .* M3(ceil(X/4));
Method three: without a loop using repelem:
Z = M1 .* repelem(M2,2) .* repelem(M3,4)
For example, method two:
>> M1 = 1:1:8
M1 =
1 2 3 4 5 6 7 8
>> M2 = 11:11:44
M2 =
11 22 33 44
>> M3 = [111,222]
M3 =
111 222
>> X = 1:numel(M1);
>> Z = M1 .* M2(ceil(X/2)) .* M3(ceil(X/4))
Z =
1221 2442 7326 9768 36630 43956 68376 78144

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by