Samaneh Rezaei
Samaneh Rezaei

Reputation: 83

How can I declare 2-dimentional array as parameter in function In MATLAB?

I have a function that gets a matrix and do some operations on it. but I do not know how to declare function's parameter . this is my function Code:

function D=Shirinkage(a)
    D(1,:)=a(1,:);%this is X1
    for i=2:4
        D(i,4)=0;
        for j=1:3
            D(i,j)=1/2*(a(1,j)+a(i,j));
            D(i,4)=D(i,j)^2 + D(i,4); %object function
        end
     end
end

I tried a(4,4) instead of a (parameter of the function),but the error does not appear. Error:

??? Input argument "a" is undefined.

Error in ==> Shirinkage at 3
    D(1,:)=a(1,:);%this is X1

also I want to declare D correctly.

appreciating any help.

Edited: i call my function from a script file , in this way: I have a 2-dimention array(matrix) its size is : 4*4 and its name is A. i want my function gets this matrix and do the operation on it and the result can be saved again in it.

A=Shirinkage(A)

e.x. A has this values:

A=[1,2,3,4;2,3,4,5;5,6,7,8;1,2,3,4]

Upvotes: 0

Views: 43

Answers (1)

nahomyaja
nahomyaja

Reputation: 202

The function you created is working fine. The only recommendation I have to pre-allocate the size of D as it varies in each iteration in your current code.

function D = Shirinkage(a)
    D = zeros(size(a));
    D(1,:) = a(1,:);                        %this is X1
    for i = 2:4
        D(i,4) = 0;
        for j = 1:3
            D(i,j) = 0.5*(a(1,j) + a(i,j));
            D(i,4) = D(i,4) + D(i,j)^2;     %object function
        end
     end
end

The function was called from command window by using the same matrix you have used and it gave the following output.

Output

The error you have posted says that the function hasn't received the argument a. If your script and the function are in the same MATLAB path, this should work perfectly.

Upvotes: 1

Related Questions