MATLAB Matlab Problem with loops and genvarname

  • Thread starter Thread starter Zayri7
  • Start date Start date
  • Tags Tags
    Loops Matlab
AI Thread Summary
The discussion revolves around a MATLAB coding issue related to image processing. The user is attempting to generate multiple matrices (C, C1, C2) by subtracting matrix B from matrix A in a loop. However, they encounter an error when trying to access these matrices as if they were cell arrays. The confusion arises from the incorrect assumption that C, C1, and C2 can be treated as cell array elements. The solution provided clarifies that these matrices are not structures and should be accessed directly. Instead of using `genvarname` and `eval`, a more straightforward approach is suggested, utilizing `sprintf` to dynamically create variable names and perform calculations within the loop. This method allows for proper referencing of the generated matrices without encountering errors.
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?
 
Physics news 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.
 
Back
Top