Matlab Problem with loops and genvarname

  • Context: MATLAB 
  • Thread starter Thread starter Zayri7
  • Start date Start date
  • Tags Tags
    Loops Matlab
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 replies · 7K views
Zayri7
Messages
1
Reaction score
0
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 I am 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 I am 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 don't know what to do. Can someone help me?
 
on Phys.org
Ok i don't 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 isn't 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.