I want to build a file name from cell arrays. I wanted to use sprintf function, but it doesn't work for cell inputs (it works well for example for string arrays).
Example:
foldername = sprintf('''\\STH\\Sth %s\\ABC %s;'',firstvariable,secondvariable);
Output:
Error using sprintf
Function is not defined for 'cell' inputs.
Where variables are cell arrays, like that:
firstvariable = {'A','B','C'};
secondvariable = {'D','E','F'};
I also tried to use fullfile function, but it doesn't take any variables. The output from this one look like that: \STH\Sth %s\ABC %s. What more, I also tried to use strcat function, but the result is pretty the same.
Do you have any other ideas how it can be done?
Thanks!
You can pass the two cell arrays to cellfun to loop over them at the same time:
firstvariable = {'A','B','C'};
secondvariable = {'D','E','F'};
foldername = cellfun(#(x,y) ['\STH\Sth ' x '\ABC ' y], firstvariable, secondvariable, 'UniformOutput', false);
This gives
foldername =
1×3 cell array
'\STH\Sth A\ABC D' '\STH\Sth B\ABC E' '\STH\Sth C\ABC F'
Is this what you want?
for ii = 1:length(firstvariable)
foldername{ii} = sprintf('''\\STH\\Sth %s\\ABC %s;''',firstvariable{ii},secondvariable{ii});
end
The output is:
foldername = {''\STH\Sth A\ABC D;''} {''\STH\Sth B\ABC E;''} {''\STH\Sth C\ABC F;''}
To use any of the folder names just do the following:
foldername{index} % Gives back a string
foldername(index) % Gives back a cell
Related
Here's a non-scalar structure in matlab:
clearvars s
s=struct;
for id=1:3
s(id).wa='nko';
s(id).test='5';
s(id).ad(1,1).treasurehunt='asdf'
s(id).ad(1,2).treasurehunt='as df'
s(id).ad(1,3).treasurehunt='foobar'
s(id).ad(2,1).treasurehunt='trea'
s(id).ad(2,2).treasurehunt='foo bar'
s(id).ad(2,3).treasurehunt='treasure'
s(id).ad(id,4).a=magic(5);
end
is there an easy way to test if the structure s contains the string 'treasure' without having to loop through every field (e.g. doing a 'grep' through the actual content of the variable)?
The aim is to see 'quick and dirtily' whether a string exists (regardless of where) in the structure. In other words (for Linux users): I'd like to use 'grep' on a matlab variable.
I tried arrayfun(#(x) any(strcmp(x, 'treasure')), s) with no success, output:
ans =
1×3 logical array
0 0 0
One general approach (applicable to any structure array s) is to convert your structure array to a cell array using struct2cell, test if the contents of any of the cells are equal to the string 'treasure', and recursively repeat the above for any cells that contain structures. This can be done in a while loop that stops if either the string is found or there are no structures left to recurse through. Here's the solution implemented as a function:
function found = string_hunt(s, str)
c = reshape(struct2cell(s), [], 1);
found = any(cellfun(#(v) isequal(v, str), c));
index = cellfun(#isstruct, c);
while ~found && any(index)
c = cellfun(#(v) {reshape(struct2cell(v), [], 1)}, c(index));
c = vertcat(c{:});
found = any(cellfun(#(c) isequal(c, str), c));
index = cellfun(#isstruct, c);
end
end
And using your sample structure s:
>> string_hunt(s, 'treasure')
ans =
logical
1 % True!
This is one way to avoid an explicit loop
% Collect all the treasurehunt entries into a cell with strings
s_cell={s(1).ad.treasurehunt, s(2).ad.treasurehunt, s(3).ad.treasurehunt};
% Check if any 'treasure 'entries exist
find_treasure=nonzeros(strcmp('treasure', s_cell));
% Empty if none
if isempty(find_treasure)
disp('Nothing found')
else
disp(['Found treasure ',num2str(length(find_treasure)), ' times'])
end
Note that you can also just do
% Collect all the treasurehunt entries into a cell with strings
s_cell={s(1).ad.treasurehunt, s(2).ad.treasurehunt, s(3).ad.treasurehunt};
% Check if any 'treasure 'entries exist
find_treasure=~isempty(nonzeros(strcmp('treasure', s_cell)));
..if you're not interested in the number of occurences
Depending on the format of your real data, and if you can find strings that contain your string:
any( ~cellfun('isempty',strfind( arrayfun( #(x)[x.ad.treasurehunt],s,'uni',0 ) ,str)) )
I would like to select all the variables in my workspace whos name follow a specific pattern. For example, I would like to compute the mean for all the variables in my workspace starting with the name my_vars.
I tried the following code:
a = who('-regexp','my_vars*')
result = mean(eval(a))
Howevever the eval function doesn't work for cells. Is there any work arround?
who returned a cell array of char arrays (i.e. strings), with each element containing one variable name. You need to convert that to a string containing a comma-separated list of the names. Here's one way to do that:
my_vars1 = 1; my_vars2 = 2; my_vars3 = 3;
names = who('-regexp', 'my_vars*');
namelist = sprintf('%s,', names{:}); % sprintf reuses the format string if
% there are more inputs than format specifiers
namelist(end)=[]; % strip last comma
eval(sprintf('mean([%s])', namelist))
ans =
2
Imagine a function with a variable number of input arguments, alternately asking for a string and a value.
myfunction('string1',value1,'string2',value2,...)
e.g.
myfunction('A',5,'B',10)
I want to keep the ability to call the function like that and I dont want to change the evaluation of varargin inside the function. (Except ('string1','string2',...,value1,value2,...) if that helps)
But I also have my input strings and values stored in a cell array inputvar <4x1 cell>:
inputvar =
'A' [5] 'B' [10]
Also this cell array has a variable length.
My intention is to call my function somehow as follows:
myfunction( inputvar )
which is obviously not working. Any ideas how I could transform my cell to a valid input syntax?
I already tried to generate a string like
''string1',value1,'string2',value2'
and use eval to use it in the function call. But it didn't worked out. So alternatively is there a way to transfor a string to code?
You should be able to do it like this:
myfunction(inputvar{:})
{:} creates a comma separated list
EDIT:
For example:
function val = myfunction(string1,value1,string2,value2)
if string1 == 'A'
val = value1;
else
val = value2;
end
myfunction('A',5,'B',10)
myfunction('B',5,'B',10)
A = {'A',5,'B',10};
myfunction(A{:})
A = {'B',5,'B',10};
myfunction(A{:})
returns:
ans = 5
ans = 10
ans = 5
ans = 10
I have a cell array that is a list of file names. I transposed them because I find that easier to work with. Now I am attempting to go through each line in each cell and remove the lines based on their file extension. Eventually, I want to use this list as file names to import data from. This is how I transpose the list
for i = 1:numel(F);
a = F(1,i);
b{i} = [a{:}'];
end;
The code I am using to try and read the data in each cell keeps giving me the error input must be of type double or string. Any ideas?
for i = 1:numel(b);
for k = 1:numel(b{1,i});
b(cellfun(textscan(b{1,i}(k,1),'%s.lbl',numel(b)),b))=[];
end;
end;
Thanks in advance.
EDIT: This is for MATLAB. Should have been clear on that. Thanks Brian.
EDIT2: whos for F is
Name Size Bytes Class Attributes
b 1x11 13986188 cell
while for a is
Name Size Bytes Class Attributes
a 1x1 118408 cell
From your description I am not certain how your F array looks, but assuming
F = {'file1.ext1', 'file2.ext2', 'file3.ext2', 'file2.ext1'};
you could remove all files ending with .ext2 like this:
F = F(cellfun('isempty', regexpi(F, '\.ext2$')));
regexpi, which operates on each element in the cell array, returns [] for all files not matching the expression. The cellfun call converts the cell array to a logical array with false at positions corresponding to files ending with .ext2and true for all others. The resulting array may be used as a logical index to F that returns the files that should be kept.
You're using cellfun wrong. It's signature is [A1,...,Am] = cellfun(func,C1,...,Cn). It takes a function as first argument, but you're passing it the result of textscan, which is a cell array of the matching strings. The second argument is a cell array as it should be, but it doesn't make sense to call it over and over in a loop. `cellfun´'s job is to write the loop for you when you want to do the same thing to every cell in a cell array.
Instead of parsing the filename yourself with textscan, I suggest you use fileparts
Since you're already looping over the cell array in transpose-step, it might make sense to do the filtering there. It might look something like this:
for i = 1:numel(F);
a = F(1,i);
[~,~,ext] = fileparts(a{:});
if strcmpi(ext, '.lbl')
b{i} = [a{:}'];
end
end;
My question is easily summarized as: "Why does the following not work?"
teststruct = struct('a',3,'b',5,'c',9)
fields = fieldnames(teststruct)
for i=1:numel(fields)
fields(i)
teststruct.(fields(i))
end
output:
ans = 'a'
??? Argument to dynamic structure reference must evaluate to a valid field name.
Especially since teststruct.('a') does work. And fields(i) prints out ans = 'a'.
I can't get my head around it.
You have to use curly braces ({}) to access fields, since the fieldnames function returns a cell array of strings:
for i = 1:numel(fields)
teststruct.(fields{i})
end
Using parentheses to access data in your cell array will just return another cell array, which is displayed differently from a character array:
>> fields(1) % Get the first cell of the cell array
ans =
'a' % This is how the 1-element cell array is displayed
>> fields{1} % Get the contents of the first cell of the cell array
ans =
a % This is how the single character is displayed
Since fields or fns are cell arrays, you have to index with curly brackets {} in order to access the contents of the cell, i.e. the string.
Note that instead of looping over a number, you can also loop over fields directly, making use of a neat Matlab features that lets you loop through any array. The iteration variable takes on the value of each column of the array.
teststruct = struct('a',3,'b',5,'c',9)
fields = fieldnames(teststruct)
for fn=fields'
fn
%# since fn is a 1-by-1 cell array, you still need to index into it, unfortunately
teststruct.(fn{1})
end
Your fns is a cellstr array. You need to index in to it with {} instead of () to get the single string out as char.
fns{i}
teststruct.(fns{i})
Indexing in to it with () returns a 1-long cellstr array, which isn't the same format as the char array that the ".(name)" dynamic field reference wants. The formatting, especially in the display output, can be confusing. To see the difference, try this.
name_as_char = 'a'
name_as_cellstr = {'a'}
You can use the for each toolbox from http://www.mathworks.com/matlabcentral/fileexchange/48729-for-each.
>> signal
signal =
sin: {{1x1x25 cell} {1x1x25 cell}}
cos: {{1x1x25 cell} {1x1x25 cell}}
>> each(fieldnames(signal))
ans =
CellIterator with properties:
NumberOfIterations: 2.0000e+000
Usage:
for bridge = each(fieldnames(signal))
signal.(bridge) = rand(10);
end
I like it very much. Credit of course go to Jeremy Hughes who developed the toolbox.