[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: having difficulty using a for loop to solve an equation
From: |
Thomas D. Dean |
Subject: |
Re: having difficulty using a for loop to solve an equation |
Date: |
Tue, 20 Jun 2017 00:37:53 -0700 |
User-agent: |
Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Thunderbird/52.1.1 |
On 06/19/2017 10:17 PM, Kire Pudsje wrote:
On Tue, Jun 20, 2017 at 2:26 AM, shankara naryana
<address@hidden <mailto:address@hidden>> wrote:
got rid of i and j my code looks like this:
%Vectorization
clc;
clear;
a=[1 2 3 4 5]; %array created per spec
x=a; %array created per spec
b=[-2 -1 0 1 2]; %array created per spec
y=5-2.*b; %array created per spec
z=(y+x).^3; %formula to be solved in loop
for m=a
t=z
end
Actually you already wrote the vectorized form. There is no need for the
for loop anymore
For the for loop solution, you would need to calculate the solution for
each index separately.
I do not know if my other mail came through. There are network problems
in the Netherlands.
But I think the assignment is ill-formed.
Purely from a methematical perspective, only z_1 and z_2 are defined.
It appears this assignment is to demonstrate two ways to calculate the
cube of the sum.
x = [1 2 3 4 5];
b=[-2 -1 0 1 2];
% Loop to calculate y
for idx = 1:size(b,2)
y(idx) = 5 - 2 * b(idx);
endfor
% Loop to calculate z
for idx = 1:size(y,2)
z(idx) = ( x(idx) + y(idx) ) ^ 3;
endfor
% vector method
x = 1:5;
y = ( 5 - 2 .* [-2:2] );
z = ( x + y ) .^ 3;
%Or, simply
z = ( [1:5] + ( 5 - 2 .* [-2:2] ) ) .^ 3
Tom Dean