0

I have a script that opens a folder and does some processing on the data present. Say, there's a file "XYZ.tif".

Inside this tif file, there are two groups of datasets, which show up in the workspace as

data.ch1eXYZ

and

data.ch3eXYZ

If I want to continue with the 2nd set, I can use A=data.ch3eXYZ

However, XYZ usually is much longer and varies per file, whereas data.ch3e is consistent.

Therefore I tried A=strcat('data.ch3e','origfilename'); where origfilename of course is XYZ, which has (automatically) been extracted before.

However, that gives me a string A (since I practically typed

A='data.ch3eXYZ'

instead of the matrix that data.ch3eXYZ actually is. I think it's just a problem with ()'s, []'s, or {}'s but Ican't seem to figure it out.

Thanks in advance!

3
  • It seems hard to avoid eval in this case. Try eval(['A = ' strcat('data.ch3e','origfilename') ';']) Commented Jun 27, 2014 at 14:18
  • Ah, the infamous eval. It works perfectly btw! Thanks for including the ';' too, probably would not have figured out where exactly to put it in. Eval keeps confusing me, maybe I'll remember this time. Commented Jun 27, 2014 at 14:25
  • As a general rule, if you need eval you probably should be doing things differently so that you don't need it. In this case, maybe use cells instead of fields. Oh, I see now that @excaza's answer solves it with dynamic field names. Clever Commented Jun 27, 2014 at 14:33

1 Answer 1

3

If you know the string, dynamic field references should help you here and are far better than eval

Slightly modified example from the linked blog post:

fldnm = 'fred';
s.fred = 18;
y = s.(fldnm)

Returns:

y =

    18

So for your case:

test = data.(['ch3e' origfilename]);

Should be sufficient

Edit: Link to the documentation

Sign up to request clarification or add additional context in comments.

2 Comments

See, I didn't need a solution to my problem, just the correct way of what I wanted to do. Thanks a lot, works like a charm! :)
@user3783502 It really should be better documented, I used MATLAB for more than 6 years before I discovered the syntax. It's extremely powerful on its own, even more so when compared to eval, which is generally used in its place.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.