MATLAB Problem storing array value in MATLAB

AI Thread Summary
The discussion centers on a MATLAB function designed to calculate weights based on input parameters. The original function fails to store results in an array when the input is a vector because it uses conditions that apply to the entire array rather than individual elements. The solution involves modifying the function to include a loop that processes each element of the input vector separately. A corrected version initializes an output array and iterates through the input, applying the weight calculations conditionally for each element. This approach successfully allows the function to return an array of weights, resolving the initial issue.
geft
Messages
144
Reaction score
0
I have the following function

Code:
function [W] = calcw(k1,k2,d,x)

if x<d
    W = k1*x;
elseif x>=d
    W = k1*x+2*k2*(x-d);
end;

save('varw.mat');

with the following script
Code:
k1 = 10e4;
k2 = 1.5e4;
d = 0.1;
x = 0:0.01:0.3;
    
weight = calcw(k1,k2,d,x);

plot(weight,x);

but the problem is that the W values refuse to be stored in the weight variable in the form of an array. The code works if x is a single value, but it doesn't since x is an array. Any help please?
 
Physics news on Phys.org
When you use a comparison on an array the way you currently have it, MATLAB will only evaluate the code under the condition if it is true for every element in the array.

Code:
if x<d
    W = k1*x; % This will only happen if *all* elements of x < d
elseif x>=d
    W = k1*x+2*k2*(x-d); % This will only happen if all elements of x >= d
end
I suspect you want to create a vector W that weights the individual elements of the input x vector. You'll need a for loop and to access the individual members of the x vector then.
 
Do you mean using something like this?

Code:
for i = 1:length(x)
weight[i] = calcw(k1,k2,d,x[i]);
end;

I keep getting parse errors for the '=' and ')'.
 
Your syntax is incorrect. In MATLAB, to call an element of a matrix/vector, use
Code:
% Vector (i.e. a 1 x n or n x 1 matrix)
someElement = vector(i); % i is some integer 1< i < length(matrix)
% Matrix
someElement = matrix(i,j); % i,j are ints such that 1<i<number of rows and 1<j<number of columns

I would vectorize the function instead, like this:
Code:
function [W] = calcw(k1,k2,d,x)
    W = zeros(1,length(x)); % initialize W
    for i=1:length(x);
        if x(i)<d
            W(i) = k1*x(i);
        elseif x(i)>=d
            W(i) = k1*x(i)+2*k2*(x(i)-d);
        end % end if
    end % end for
end % end function
Then you can just call:
Code:
weight = calcw(k1,k2,d,x);
 
Last edited:
It works! Many thanks :)
 

Similar threads

Replies
18
Views
4K
Replies
4
Views
2K
Replies
1
Views
2K
Replies
1
Views
1K
Replies
4
Views
1K
Replies
2
Views
2K
Back
Top