Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Matlab Problem with loops and genvarname

  1. Aug 15, 2010 #1
    I've been stuck for weeks on a code that I have been generating for image processing. And made an example of what I need. I have this code: (BTW Im new to this matlab world)


    A = [2, 5, 6; 3,6,7];

    B = [5, 3, 1; 7,3,2];

    for i=1:3

    v = genvarname('C', who);

    eval([v '= A-B'])

    end
    The part above ^^^^ gives me this:

    C =

    -3 2 5
    -4 3 5

    C1 =

    -3 2 5
    -4 3 5

    C2 =

    -3 2 5
    -4 3 5

    This is the part im having problem explaining.

    I want to do something like this:

    for n=1:3

    F{n} = C{n}(2,1) + B(2,1)

    end
    But it tells me:

    Cell contents reference from a non-cell array object.
    I really dont know what to do. Can someone help me?
     
  2. jcsd
  3. Mar 3, 2012 #2
    Ok i dont know if you have solved this yet, but looking at the date on the post, you might have but someone may still be looking for something similar.

    The reason why this isnt working is already explained in the matlab error statement generated when you run this.

    If i understand you correctly you want c{n} to run like c1, c2 and c3.

    Just ignoring the fact that this is wrong, even if it were right you would still get an error. There is no C3. You generate C C1 and C2. Moreover C, C1 and C2 can not be structures, they are simple matrices. elements of structures are accessed through c{n}

    Now to the part how can you get C C1 and C2 is as follows:

    clear all;
    clc;
    A = [2, 5, 6; 3,6,7];
    B = [5, 3, 1; 7,3,2];
    for i=1:3
    eval(sprintf('C%d = A-B',i))
    eval(sprintf('F{i} = C%d(2,1)+B(2,1)',i))
    end

    dont use %v = genvarname('C', who); eval alone can do the job for you.
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook