Increment different rates in same for-loop

조회 수: 1 (최근 30일)
Niclas Madsen
Niclas Madsen 2018년 10월 1일
편집: Stephen23 2018년 10월 2일

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
ANKUR KUMAR
ANKUR KUMAR 2018년 10월 1일
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;

댓글을 달려면 로그인하십시오.

채택된 답변

Niclas Madsen
Niclas Madsen 2018년 10월 2일
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

추가 답변 (1개)

Stephen23
Stephen23 2018년 10월 2일
편집: Stephen23 2018년 10월 2일
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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by