capturing data in cell arrays in matlab - matlab

I am trying to store cell array output of a function into another cell array but couldn't do it. Here is a sample code:
clear all; close all; clc;
b1=cell(1,3);
%b1=t1()
[b1{1,1},b2{1,2},b{1,3}]=t1(); %%l1
function [ op1 ] = t1( )
op1=cell(3,1);
op1{1}=10;
op1{2}=20;
op1{3}=30;
end
Function t1 outputs a 3x1 cell array. In line l1 I am trying to capture that array into column format array (1x3), but getting error. Anyone knows way to do this?

You are requesting three outputs from t1 when it only returns one. You should store the output in a temporary variable prior to saving the values into three different cell arrays. To perform that assignment you can use {:} indexing to yield a comma-separated list that you can then assign to all the different cell arrays
output = t1();
[b1{1,1}, b2{1,2}, b{1,3}]= output{:};
Your other option is to actually return three outputs from t1
function [out1, out2, out3] = t1( )
out1 = 10;
out2 = 20;
out3 = 30;
end
[b1{1,1}, b2{1,2}, b{1,3}] = t1();

Related

How to take transpose of N-D array in matlab?

I am using the following code to get all the possible combinations of the rows of a matrix.
function rComb(matrix)
rows = size(matrix,1)
for n = 1:rows
rowsCell = num2cell(matrix,2);
r = nchoosek(1:size(matrix,1),n);
out = cell2mat(reshape(rowsCell(r.',:).',n,1,[]))
end
end
Now I want to take the transpose of the out variable, and I am using this code.
function rComb(matrix)
rows = size(matrix,1)
for n = 1:rows
rowsCell = num2cell(matrix,2);
r = nchoosek(1:size(matrix,1),n);
out = cell2mat(reshape(rowsCell(r.',:).',n,1,[]))
transp = out'
end
end
And I am facing this error...!!
"Error using '
Transpose on ND array is not defined. Use PERMUTE
instead."
Can you solve this issue?
One more thing can a function give us multiple outputs like all the possible combinations of output? Like in the above code if I place ';' after out variable statement this function won't display anything :/.

matlab vectorization if statement

Can someone please tell me the vectorized implementation of following matlab code. Predicted is an array containing either of the two values "pos" or "neg". I have to copy the values when condition comes true.
p = 1;
box = zeros(size(bbox));
for k = 1: size(predicted)
if predicted(k) == 'pos'
box(p,:) = bbox(k,:);
p = p + 1;
end
end
bbox=rand(100); %demo data
predicted = rand(1,100)>0.5; %logical values
%You want to convert your array of strings into an array of logical values
%predicted=strcmp(predicted,'pos');
box=bbox(predicted,:);

How to gather results with parfor in MATLAB

I have a function called SpreadFinder which returns an array of structures:
[ spreads ] = SpreadFinder( pp, corr_thres, i_range )
The return object looks like this:
spreads =
1x4026 struct array with fields:
px
tuple
beta
The code is:
m = containers.Map(0, 0, 'uniformValues',false); m.remove(0);
parfor col = 1:8
spreads = SpreadFinder(pp, 0.8, i_ranges(:,col)');
m(col) = spreads;
end
When I run it, I have this error:
Subscripted assignment dimension mismatch.
I know the Map can be used to store an array of structures. (https://stackoverflow.com/a/2365526)
This code below works. So I don't think it's a problem of dimension...
m(1) = spreads(1:2);
m(2) = spreads(1:4);
The objective is to merge all the results into one map and possibly iterate over this map after the parallel task.
Can someone help me out?
Best,
IIRC, you cannot assign to a containers.Map inside a parfor because a containers.Map is not sliceable. If you want to assign elements to an array inside a parfor, it must be sliceable. What I mean by sliceable is that you are able to extract a subset of the values via the colon operator (i.e. 1:3, 2:4), etc. You cannot do that with a containers.Map unless you specifically use the values function, and from there you can specify a cell array of keys and get the values from there. Using () syntax only permits you to access one key at a time.
Therefore, what I would suggest you do is assign the outputs to a cell array, and use this cell array as values into your containers.Map. Something like this:
%// Create temporary cell array of values
c = cell(1,8);
%// Run parfor for each col
parfor col = 1:8
c{col} = SpreadFinder(pp, 0.8, i_ranges(:,col)');
end
%// Make a new containers.Map for these values
m = containers.Map(1:8, c, 'uniformvalues', false);
%clear c; %// Optional if you don't want the temporary cell array to stick around

Matlab - difficulty getting output for my function

I am trying to write a function transform(A) which when given a matrix A returns a new matrix. The new matrix should be obtained according to following:
if A has more than one row then interchange the first and second row. After this square the elements in the first row.
So far thats what I have written:
function[Anew] = transform(A)
dimension = size(A);
if dimension(1) > 1 %if there is more than 1 row
A([1 2],:)=A([2 1],:);
end
A(1,:,:) = A(1,:,:).^2 %squares elements in the first row
end
I tested my function by invoking it in matlab.
I noticed that because i dont have a semi colon next to A(1,:,:) = A(1,:,:).^2
I still obtain the desired result but not as output of the function.
I obtain A =
instead of Anew =
If i put a semi colon next to A(1,:,:) = A(1,:,:).^2; then I dont get an output at all.
Could you tell me what is wrong and what should I change in my program to obtain output as Anew?
Thank you
To return a value from a function in Matlab, you must directly assign to it.
In your case, you need to assign to Anew at the end of the operation (you could also technically just use that variable all-together).
function [Output1, Output2] = SomeFunction( ... )
% Do Some Work
% Store Output
Output1 = Result1(:,2) %some output
Output2 = Result2(3:end, :) %some other result
end
function[Anew] = transform(A)
dimension = size(A);
Anew = A;
if dimension(1) > 1 %if there is more than 1 row
Anew ([1 2],:)=Anew([2 1],:);
end
Anew(1,:,:) = Anew(1,:,:).^2; %squares elements in the first row
end

Using varargin inputs as structure name and string

Is there a way to use varargin inputs in several different forms. I would like the varargin inputs to become the name of a structure, but I also want it be passed into a fprintf which doesn't accept cell or structure arrays. If I have a function like:
function[] = myfunc(varargin)
for k = varargin
for m = 'ABC'
for n = 1:10
varname = sprintf('%c%d',m,n);
filename = sprintf('Images\\%s',varname);
fprintf('Take measurement %s for %s\n',k,varname);
image = imread(fullfile(filename));
pause
cursor_info = evalin('base','cursor_info');
p1 = cursor_info(2).Position
p2 = cursor_info(1).Position
[d,s] = measure(p1,p2) %measure is a separate function in my directory
k.(varname) = [d,s]
end
end
save('Distances,'k','-append')
end
My function is used to analyze several pictures, hence the ABC and 1:10 for loops. If I call the function with inputs of 'M1', 'M2', 'M3', I would like the function to create structures M1, M2, and M3 with A1,B1,C1 - A10,B10,C10 as the field names. [d,s] will be the data saved in each field which is found with the imagesc GUI and function measure.
The problem is that in the loop iterations I want the varargin inputs to be inputed into fprintf and I also want the varargin inputs to become the structure name. I can edit the code so that fprintf accepts the inputs using the function char. But is it possible to have an input in a function become the name of structure to fill with data? And if so, the solution still has to allow the iterator k to be passed into fprintf.
You can have a single structure that holds all k-s, then you can save it with '-struct' option to "strip" it into its fields:
function[] = myfunc(varargin)
for k = varargin
for m = 'ABC'
for n = 1:10
% your stuff here... I am too lazy to copy it...
[d,s] = measure(p1,p2) %measure is a separate function in my directory
meta.(k{1}).(varname) = [d,s] ; % note the {1} for k, loop over cell elements
end
end
save('Distances','meta','-struct','-append'); % not 100% sure -append wirks with -struct, you'll have to verify that...
end