for loop for matrix

1 view (last 30 days)
I CHUN LIN
I CHUN LIN on 11 Aug 2020
Answered: hosein Javan on 11 Aug 2020
Hello everyone, I have 3 matrix:
x = [1, 2, 5];
y = [0.1, 0.5, 10];
z = [10 20; 30 40];
and one output:
a = z./x + z./y
I want to get the result:
a = 10/1 +10/0.1 = 110, a = 20/1 +20/0.1 = 220
a = 10/2 +10/0.5 = 25, a = 20/2 +20/0.5 = 50
a = 10/5 +10/10 = 3, a = 20/5 +20/10 = 6
a = 30/1 +30/0.1 = 330, a = 40/1 +40/0.1 = 440
a = 30/2 +30/0.5 = 75, a = 40/2 +40/0.5 = 100
a = 30/5 +30/10 = 9, a = 40/5 +40/10 = 12
that is,
a = [110, 25, 3; 220, 50, 6; 330, 75, 9; 440,100,12]
I tried this by for loop
clear
clc
for x = [1; 4; 6; 7; 8; 9]
for y = [13; 26; 45; 62; 70; 89]
z = [0.1 0.01; 0.01 0.1];
a = z./x + z./y
end
end
but getting "Matrix dimensions must agree."
How can I solve this problem? Thank you very much!
  1 Comment
SAMARTH MAHESHKUMAR GEMLAWALA
for element wise division of matrix, dimensions of both matrix must be same. in your case z in 2 * 2 matrix and x is 6 * 1 matrix and y is 6 * 1 matrix.

Sign in to comment.

Answers (1)

hosein Javan
hosein Javan on 11 Aug 2020
x = [1, 2, 5]
y = [0.1, 0.5, 10]
z = [10 20; 30 40]
X = repmat(x,[4 1])
Y = repmat(y,[4 1])
Z = repmat(z(:),[1 3])
a = Z./X + Z./Y

Categories

Find more on Creating and Concatenating Matrices 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!