Naming variables with other variables

  • Thread starter Thread starter Odysseo
  • Start date Start date
  • Tags Tags
    Variables
Click For Summary

Discussion Overview

The discussion revolves around a programming challenge related to naming variables dynamically in MATLAB, specifically within the context of using double loops to process datasets associated with different sources. Participants explore methods for constructing variable names based on existing variables and handling datasets.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • One participant describes their attempt to create new datasets by dynamically naming them using both source names and group identifiers, but encounters issues with their approach.
  • Another participant questions the programming language used and suggests that if it were C or Java, proper braces would be necessary for the loops, indicating a potential misunderstanding of the syntax.
  • A participant confirms that the code is written in MATLAB and emphasizes the need to dynamically create variable names and search for datasets, rather than focusing solely on loop structure.
  • Another participant provides examples from MATLAB documentation on constructing filenames and suggests avoiding the use of eval for this purpose.
  • One participant proposes a modification to the original code that involves using eval to assign values to variables dynamically, but it remains unclear if this resolves the initial issue.
  • The original poster later indicates they have rewritten the code in Python, suggesting a shift in approach, but does not elaborate on the specifics of the solution.

Areas of Agreement / Disagreement

Participants do not reach a consensus on the best method for dynamically naming variables in MATLAB, and there are multiple competing views on the use of eval and the overall approach to the problem.

Contextual Notes

There are limitations regarding the assumptions made about the programming language and the specific requirements for checking dataset existence, which remain unresolved in the discussion.

Odysseo
Messages
3
Reaction score
1
Hallo, this is my first thread here. I have to do a double loop.
I've a 1x4 cell containing 4 sources. For each of this sources i have a number of dataset labeled as source_pN where N is a number (a label for a group). I have to do a double "for" loop on sources and on each existing N to create another dataset with histc on previous dataset variables. So i would like to name those new datasets using both source name and N number. I've done something like this:

Matlab:
sources = {'BKG' 'Ba133' 'Co57' 'Cs137'};

for is = 1:length(sources)

    sourcename = sources{is};
    source = eval(sprintf('%spixels', sourcename));
    source.groups = source.nx*100+source.ny;

    for grp = 1:length(unique(source.groups))

        pix = source.groups(grp);

        if -SOMETHING TO CHECK WHICH N-
            data = eval(sprintf('%s_P%i',sourcename,pix));
            Qbins.data = 0:0.05:max(data.Qnet);
            Qpop.data = histc(data.Qnet, Qbins.data);
        else
            continue
        end

    end
end
But it doesn't work. How can i solve my problem? Any hints?
 
Last edited by a moderator:
Technology news on Phys.org
What language are you writing in?

I assumed it was MATLAB and added code tags and some blank lines to your post for readability of the code.

If this is in fact C or Java code then the for loops need to have braces to enclose the loop body otherwise the for will loop on the first statement only.
Java:
for(int i=0; i<10; i++)
    println("Hello");       // semi-colon denotes end of this loop
    println("goodbye ... executed once only as loop ended with previous ;...");

//         vs

for(int i=0; i<5; i++) {
    println("hello");
    println("hello again");
}    // brace denotes end of this loop
 
jedishrfu said:
What language are you writing in?

I assumed it was MATLAB and added code tags and some blank lines to your post for readability of the code.

If this is in fact C or Java code then the for loops need to have braces to enclose the loop body otherwise the for will loop on the first statement only.
Java:
for(int i=0; i<10; i++)
    println("Hello");       // semi-colon denotes end of this loop
    println("goodbye ... executed once only as loop ended with previous ;...");

//         vs

for(int i=0; i<5; i++) {
    println("hello");
    println("hello again");
}    // brace denotes end of this loop
Hi, thank you, my code is written in Matlab. Perhaps it's not properly correct, but I'm rather sure that the "for" loop is right (it stops with the "end" statement). However, my problem is to having variables named by another variables and to search for a dataset among the others (the if statement).
 
It looks like you are trying to build a filename from a string and a number.

Here's some examples from the MATLAB site:

https://www.mathworks.com/matlabcentral/newsreader/view_thread/290652

Notice they use sprintf to create a formatted string and don't need the eval.

A common programming task is to construct a filename as you have done and then check to see if the file exists by opening it or by some file exists function.

https://www.mathworks.com/matlabcentral/answers/49414-check-if-a-file-exists
 
Have you tried this (source):

Code:
sources = {'BKG' 'Ba133' 'Co57' 'Cs137'};

for is = 1:length(sources)

    sourcename = sources{is};
    eval([source  ' = ' sprintf('%spixels', sourcename) ';']); % Change here
    source.groups = source.nx*100+source.ny;

    for grp = 1:length(unique(source.groups))

        pix = source.groups(grp);

        if -SOMETHING TO CHECK WHICH N-
            eval([data ' = ' sprintf('%s_P%i',sourcename,pix) ';']); % Change here
            Qbins.data = 0:0.05:max(data.Qnet);
            Qpop.data = histc(data.Qnet, Qbins.data);
        else
            continue
        end

    end
end
 
Thank you all. Finally I've preferred to re-write the code in Python. So now works!