What does the following vector declaration means vector<vector<int>>v(100)? - stl

How can I assign single size to a 2d vector?
Also what does this imply?

v is declared to be a vector whose element type is vector<int>, and initialized to contain 100 such elements - all empty vectors. In other words, v.size() == 100, v[i].size() == 0 (for i from 0 through 99).
If you want to initialize v to contain 100 vectors, each of which contains 100 ints, you can do it this way:
std::vector<std::vector<int>> v{100, std::vector<int>{100}};

Related

Prepping the number of inputs for a function in MATLAB

For example, ndgrid has inputs as n vectors where n is decided by the user.
For my use case, n can change. I would like to prepare the input list before hand, based on n, then feed the inputs to ndgrid. How do I do that please?
For example, say I have 3 row vectors x1, x2, and x3. Then, if n=3 and I put inputs = [x1,x2,x3], and I use ndgrid(inputs) then MATLAB treats this as ndgrid([x1,x2,x3]) instead of ndgrid(x1,x2,x3). I want the latter, not the former. How do I solve this please?
When we use a cell array, for example x = {some,stuff,inside} you can unpack the cell with x{:}, in a function call, each elements of the cell will be passed as an argument: myfunction(x{:}) is equivalent to myfunction(some, stuff, inside).
In your case:
% Number of inputs
k = 3;
% Put your k input in a cell array
x = {1:3,1:3,1:3};
% If needed you can also have a dynamic output variable
X = cell(k,1);
% Get the result
[X{:}] = ndgrid(x{:})

why it is unable to modify a slice's length or capacity through a function call?

My purpose is to remove one element from specific slice, and the code is something like:
func main() {
s := []int{0, 1, 2, 3, 4}
remove(s, 3)
fmt.Println(s, len(s), cap(s))
}
func remove(s []int, idx int) {
if idx < 0 || idx >= len(s) {
return
}
copy(s[idx:], s[idx+1:])
s = s[:len(s)-1]
fmt.Println(s, len(s), cap(s))
}
but the output showed:
[0 1 2 4] 4 5
[0 1 2 4 4] 5 5
As I know, slice will be passed to a function call as reference type, why it is not able to modify it?
Slice holds three values:
1) pointer to underlying array
2) length
3) capacity
When you pass slice to a function, you are passing a copy of all three of those values. Therefore, you cannot change length and capacity, but since you have the pointer to the underlying array you can change values inside the array.
Slice is not a pointer type. Under the hood slice consists of 3 values: length, capacity and pointer to the array. When you pass it by value, you get copies of length and capacity - you can change them for you. Changes to array will be visible outside of the function.
And if produces such results
It's important to note that YES you can indeed change the length and capacity of a Slice or Map within a function when they are passed as parameters. However, those changes aren't visible outside of the function. When you lengthen a slice inside the function call, you're modifying a copy of the length variable that the slice holds. Memory wise, you can modified the slice but when you iterate over it after the function call you'll only be able to look at values up to the original length.

Prove using induction that the loop invariant holds

//Precondition: n > 0
//Postcondition: returns the minimum number of decial digits
// necessary to write out the number n
int countDigits(int n){
1. int d = 0;
2. int val = n;
3. while(val != 0){
4. val = val / 10; // In C++: 5 / 2 === 2
5. d++;
6. }
7. return d;
}
Invariant: Just before evaluating the loop guard on line 3, n with its rightmost d digits removed is identical to val. (Assume that the number 0 takes 0 digits to write out and is the only number that takes 0 digits to write out).
Prove using induction that the loop invariant holds.
Now I've always thought that proof with induction is assuming that by replacing a variable within an equation with k will be true then I must prove k+1 will also be true. But I'm not really given an equation in this question and just a block of code. Here's my base case:
Just before evaluating the loop guard on line 3, d is equal to 0 and on line 2, val == n, so if n has its rightmost 0 digit removed, it is val. Therefore, the base case holds.
I'm not really sure how to write the inductive step after this since I'm not sure how to prove k+1..
The logic is really the same as with an equation, except you replace the k value in your equation by the n iteration of the loop:
base case is that the loop invariant holds before starting the loop;
you have to prove that if the invariant holds before iteration N, it will still hold after execution of iteration N.
From 1. and 2. we conclude by induction that the invariant holds at the end of the loop (or at the end of any iteration, in fact).
EDIT and this is interesting because the loop ends with val == 0. Your invariant (still true at the end of the loop) is n with its rightmost d digits removed is identical to val, so n with d digits removed is identical to 0 at this point, so d is correctly the number of digits required to display n.

How to write arbitrary datatypes into Matlab cell array

This is a general question, not related to a particular operation. I would like to be able to write the results of an arbitrary function into elements of a cell array without regard for the data type the function returns. Consider this pseudocode:
zout = cell(n,m);
myfunc = str2func('inputname'); %assume myfunc puts out m values to match zout dimensions
zout(1,:) = myfunc(x,y);
That will work for "inputname" == "strcat" , for example, given that x and y are strings or cells of strings with appropriate dimension. But if "inputname" == "strcmp" then the output is a logical array, and Matlab throws an error. I'd need to do
zout(1,:) = num2cell(strcmp(x,y));
So my question is: is there a way to fill the cell array zout without having to test for the type of variable generated by myfunc(x,y ? Should I be using a struct in the first place (and if so, what's the best way to populate it)?
(I'm usually an R user, where I could just use a list variable without any pain)
Edit: To simplify the overall scope, add the following "requirement" :
Let's assume for now that, for a function which returns multiple outputs, only the first one need be captured in zout . But when this output is a vector of N values or a vector of cells (i.e. Nx1 cell array), these N values get mapped to zout(1,1:N) .
So my question is: is there a way to fill the cell array zout without having to test for the type of variable generated by myfunc(x,y) ? Should I be using a struct in the first place (and if so, what's the best way to populate it)?
The answer provided by #NotBoStyf is almost there, but not quite. Cell arrays are the right way to go. However, the answer very much depends on the number of outputs from the function.
Functions with only one output
The function strcmp has only one output, which is an array. The reason that
zout{1,:} = strcmp(x,y)
gives you an error message, when zout is dimensioned N x 2, is that the left-hand side (zout{1,:}) expects two outputs from the right-hand side. You can fix this with:
[zout{1,:}] = num2cell(strcmp(x,y)); % notice the square brackets on the LHS
However, there's really no reason to do this. You can simply define zout as an N x 1 cell array and capture the results:
zout = cell(1,1);
x = 'a';
y = { 'a', 'b' };
zout{1} = strcmp(x,y);
% Referring to the results:
x_is_y_1 = zout{1}(1);
x_is_y_2 = zout{1}(2);
There's one more case to consider...
Functions with multiple outputs
If your function produces multiple outputs (as opposed to a single output that is an array), then this will only capture the first output. Functions that produce multiple outputs are defined like this:
function [outA,outB] = do_something( a, b )
outA = a + 1;
outB = b + 2;
end
Here, you need to explicitly capture both output arguments. Otherwise, you just get a. For example:
outA = do_something( [1,2,3], [4,5,6] ); % outA is [2,3,4]
[outA,outB] = do_something( [1,2,3], [4,5,6] ); % outA is [2,3,4], outB is [6,7,8]
Z1 = cell(1,1);
Z1{1,1} = do_something( [1,2,3], [4,5,6] ); % Z1{1,1} is [2,3,4]
Z2 = cell(1,2);
Z2{1,1:2} = do_something( [1,2,3], [4,5,6] ); % Same error as above.
% NB: You really never want to have a cell expansion that is not surrounded
% by square brackets.
% Do this instead:
[Z2{1,1:2}] = do_something( [1,2,3], [4,5,6] ); % Z2{1,1} is [2,3,4], Z2{1,2} is [6,7,8]
This can also be done programmatically, with some limits. Let's say we're given function
func that takes one input and returns a constant (but unknown) number of outputs. We
have cell array inp that contains the inputs we want to process, and we want to collect the results in cell around outp:
N = numel(inp);
M = nargout(#func); % number of outputs produced by func
outp = cell(N,M);
for i=1:N
[ outp{i,:} ] = func( inp{i} );
end
This approach has a few caveats:
It captures all of the outputs. This is not always what you want.
Capturing all of the outputs can often change the behavior of the function. For example, the find function returns linear indices if only one output is used, row/column indices if two outputs are used, and row/column/value if three outputs are used.
It won't work for functions that have a variable number of outputs. These functions are defined as function [a,b,...,varargout] = func( ... ). nargout will return a negative number if the function has varargout declared in its output list, because there's no way for Matlab to know how many outputs will be produced.
Unpacking array and cell outputs into a cell
All true so far, but: what I am hoping for is a generic solution. I can't use num2cell if the function produces cell outputs. So what worked for strcmp will fail for strcat and vice versa. Let's assume for now that, for a function which returns multiple outputs, only the first one need be captured in zout – Carl Witthoft
To provide a uniform output syntax for all functions that return either a cell or an array, use an adapter function. Here is an example that handles numeric arrays and cells:
function [cellOut] = cellify(input)
if iscell(input)
cellOut = input;
elseif isnumeric(input)
cellOut = num2cell(input);
else
error('cellify currently does not support structs or objects');
end
end
To unpack the output into a 2-D cell array, the size of each output must be constant. Assuming M outputs:
N = numel(inp);
% M is known and constant
outp = cell(N,M);
for i=1:N
outp(i,:) = cellify( func( inp{i} ) ); % NB: parentheses instead of curlies on LHS
end
The output can then be addressed as outp{i,j}. An alternate approach allows the size of the output to vary:
N = numel(inp);
% M is not necessary here
outp = cell(N,1);
for i=1:N
outp{i} = cellify( func( inp{i} ) ); % NB: back to curlies on LHS
end
The output can then be addressed as outp{i}{j}, and the size of the output can vary.
A few things to keep in mind:
Matlab cells are basically inefficient pointers. The JIT compiler does not always optimize them as well as numeric arrays.
Splitting numeric arrays into cells can cost quite a bit of memory. Each split value is actually a numeric array, which has size and type information associated with it. In numeric array form, this occurs once for each array. When the array is split, this incurs once for each element.
Use curly braces instead when asigning a value.
Using
zout{1,:} = strcmp(x,y);
instead should work.

Matlab - how to make this work for both scalars and vectors

Suppose function g takes a function f as a parameter, and inside g we have something like
x = t*feval(f, u);
however, f can be either scalar-valued or vector-valued. If it is vector valued, we want x to be a vector as well, i.e. the feval statement to return the whole vector returned by f. How do we make this work for both scalar and vector cases?
As far as I can tell, what you are asking is already the default behavior in matlab.
This means that if f returns a scalar, x will be a scalar and if it returns a vector x will be a vector.
In your example, this holds as long as t is also a scalar - otherwise the result will depend on how t*[output of f] is evaluated.
Example
function o1 = f(N)
o1 = zeros(1,N);
end
Here f returns a scalar if N=1 and a vector for N>1.
Calling your code gives
x=feval('f', 1); % Returns x = 0
x=feval('f', 4); % Returns x = [0 0 0 0]
If the output of feval(f,u) can be either a scalar or a vector, and you want the result x to be the same (i.e. a scalar or a vector of the same length and dimension), then it will depend on what t is:
If t is a scalar, then what you have is fine. You can use either of the operators * or .* to perform the multiplication.
If t is a vector of the same length and dimension as the result from feval(f,u), then use the .* operator to perform element-wise multiplication.
If t is a vector of the same length but with different dimension that the result from feval(f,u) (i.e. one is a row vector and one is a column vector), then you have to make the dimensions match by transposing one or the other with the .' operator.
If t is a different length than the result of feval(f,u), then you can't do element-wise multiplication.