Having issue with the num2str function in Octave.
My code:
>> alpha = zeros(1,length(alpha));
>> legendInfo = zeros(1,length(alpha));
>> legendInfo(1) = num2str(alpha(1));
Error Message:
error: A(I) = X: X must have the same size as I
I've been trying to follow this link to no avail: Link
Update:
Based on suggestion, I have implemented the following code and have received the following error message:
>> labelInfo = cell(1,numel(alpha))
>> labelInfo{1} = num2str(alpha{1});
error: matrix cannot be indexed with {
error: evaluating argument list element number 1
ANSWER
The answer provided was accurate with one tweak:
alpha{1} (Incorrect syntax)
alpha(1) (Correct Syntax)
Parantheses rather than curly braces.
Thanks!
You have initialized legendInfo to be a numeric array the same size as alpha. When you convert alpha(1) to a string, it is possibly more than 1 character long (i.e. alpha(1) > 9) which is obviously not going to fit into a single element in an array.
length(num2str(10))
% 2
length(legendInfo(1))
% 1
Also, even if num2str(alpha(1)) yields a string that has a length of 1, it will implicitly convert it to a number (it's ASCII representation) which is likely not what you want.
legendInfo = zeros(1, numel(alpha));
legendInfo(1) = num2str(1);
% 49 0 0
Rather than a numeric array, you likely want a cell array to hold the legend info since you will have strings of varying lengths.
legendInfo = cell(1, numel(alpha));
legendInfo{1} = num2str(alpha{1});
If you look closely at the post you have linked, you'll see that they use the curly brackets {} to perform assignment rather than parentheses () indicating that they are creating a cell array.
Related
In matlab, is it possible to make the iterative variable a cell array? is there a workaround? This is the code I ideally want, but throws errors:
dim={};
a=magic(5);
for dim{1}=1:5
for dim{2}=1:5
a(dim{:})=1; %aimed to be equivalent to a(dim{1},dim{2})=1;
end
end
for dim{1}=1:5
↑
Error: Invalid expression. When calling a function or indexing a variable, use
parentheses. Otherwise, check for mismatched delimiters.
I tested that you cannot have A(1), or A{1} or A.x as index variable. https://www.mathworks.com/help/matlab/ref/for.html doesn't explicitly prohibit that, but it doesn't allow it either.
After very slight changes on your code, this should achieve what you seem to want:
dim={};
a = magic(5);
for dim1=1:5
dim{1} = dim1;
for dim2=1:5
dim{2} = dim2;
a(dim{:})=1; %aimed to be equivalent to a(dim{1},dim{2})=1;
end
end
However, I believe the following is a slightly better solution keeping the spirit of "use a cell array to index in your array":
CV = combvec(1:5,1:5); % get all combinations from (1,1) to (5,5). 2x25 double array. This function is a part of deep learning toolbox. Alternatives are available.
CM = num2cell(CV); % 2x25 cell array. Each element is a single number.
for dim = CM
% dim is a 2x1 cell array, eg {2,3}.
a(dim{:}) = 1; % as above.
end
However, none of these are likely a good solution to the underlying problem.
it's a basic question I guess (but I'm new to Matlab), but given:
>> class(motifIndexAfterThresholds)
ans =
'double'
with :
16
8037
14340
21091
27903
34082
as the contents of that variable
I hoped to print to the same line on the matlab console the contents of that variable and some other output:
fprintf('With threshold set to %d, %d motifs found at positions %f.\n',threshold,length(motifIndexAfterThresholds), motifIndexAfterThresholds);
When I do this however, I'm getting more than one line of output:
With threshold set to 800, 6 motifs found at positions 16.000000.
With threshold set to 8037, 14340 motifs found at positions 21091.000000.
With threshold set to 27903, 34082 motifs found at positions
Can someone share the method for collapsing this double array to a single line of text that I can display on the Matlab console please?
What you need is the num2str function that is builtin MATLAB. Modify your code as below:
strThresholds = num2str(motifIndexAfterThresholds.', '%f, '); % Transpose used here since you need to make sure that motifIndexAfterThresholds is a row vector
fprintf('With threshold set to %d, %d motifs found at positions %s.\n',threshold,length(motifIndexAfterThresholds), strThresholds);
The num2str function will convert your vector to a string with the specified format. So for your given example,
strThresholds = '16.000000, 8037.000000, 14340.000000, 21091.000000, 27903.000000, 34082.000000,'
You could definitely edit the format string used in the num2str funcion to suit your needs. I would suggest using %d since you have integers in your vector
This is my code in Matlab: How could I get all values of all 5 images saved? This code only returns the last image! I tried using IM(l) but it gives me an error: In an assignment A(I) = B, the number of elements in B and I must be the same.
Amount_measurements = 5;
IM=zeros(2097152,1);
l=1;
for l=(1:Amount_measurements)
if l < 9
%index = double(0)+double(0)+double(l+1);
index = strcat(num2str(double(0)),num2str(double(0)),num2str(double(l+1)));
elseif l < 99
index = double(0)+double(l+1);
else
index = double(l+1);
end
file_name1='trial.nii.gz';
%disp(file_name1);
jesu=load_nii(file_name1);
[x,y,z] = meshgrid(1:256,1:256,1:256);
[lx,ly,lz] = meshgrid(1:2:256,1:2:256,1:2:256);
newImage = interp3(x,y,z,jesu.img,lx,ly,lz);
IM= newImage(:);
end
I want the values newImage(:) to be stored as IM1=newImage(:) IM2=newImage(:) IM3=newImage(:) IM4=newImage(:) so on... How could I go about with it?
Since you mentioned wanting a variable-length version of IM1=newImage(:) IM2=newImage(:) IM3=newImage(:) IM4=newImage(:), you're looking for a cell array. Try
IM{l} = newImage;
instead of
IM(l) = newImage(:);
The important difference is the use of braces rather than parentheses. Use a right-hand side ofnewImage(:) if you want to reshape into a vector, just newImage if you want to preserve it as a matrix.
By using IM(l) you're trying to add an entire column vector (newImage(:)) to a single element (the l-th element) in the array IM, that's why Matlab throws the error.
You should consider concatenation: since newImage(:) is a column-vector, replace
IM= newImage(:);
with
IM=[IM newImage(:)];
but at the top of the script you should also initialize IM as
IM=[];
At the end of the loop, the resulting IM will have Amount_measurements columns where 1 column = 1 newImage(:).
Note #1: this will only work if newImage(:) always has the same length.
Note #2: if you know a priori how long the vector newImage(:) is and, again, by assuming that its length never changes, you should consider preallocating the IM matrix by replacing IM=[]; with IM=zeros(X,Amount_measurements); where X is the number of elements in newImage(:). Finally, regarding the concatenation stage, you should replace IM=[IM newImage(:)]; with IM(:,l)=newImage(:).
Note #3: as instead, if the size of newImage(:) can change you cannot rely on preallocation and matrices, but you must use cell arrays: the last instruction in your loop should be IM{l}=newImage(:);.
Consider the following MATLAB struct:
a(1).num=1; a(2).num=2; a(3).num=3;
The thing I want to do is to replace some of the elements of num with the old value minus a (scalar) number. For example, I would like to subtract 1 from a(2).num and a(3).num.
I already tried different ways:
a(2:3).num=a(2:3).num-1;
??? Error using ==> minus Too many input arguments.
Next try:
>>a(2:3).num=[a(2:3).num]-1;
??? Insufficient outputs from right hand side to satisfy comma separated list
expansion on left hand side. Missing [] are the most likely cause.
And last:
>> [a(2:3).num]=[a(2:3).num]-1;
??? Error using ==> minus
Too many output arguments.
arrayfun couldn´t help either.
Probably there is a quite easy answer to this question, but I couldn´t find any.
Easiest is a two-line solution:
C = num2cell([a(2:3).num]-1);
[a(2:3).num] = C{:}
Nicest is to have a function like deal, but with a function applied to each argument:
function varargout = fcnDeal(varargin)
%// (Copied from MATLAB's deal()
if nargin==1,
varargout = varargin(ones(1,nargout));
else
if nargout ~= nargin-1
error('fcnDeal:narginNargoutMismatch',...
'The number of outputs should match the number of inputs.')
end
%//...Except this part
varargout = cellfun(varargin{1}, varargin(2:end), 'UniformOutput', false);
end
end
Then what you want to do is just a matter of
[a(2:3).num] = fcnDeal(#(x)x-1, a(2:3).num)
You can manipulate them in the loop
index = [1,2]
for i = index
a(i).num = a(i).num - 1;
end
Why does ishandle return 1 for double input? For example:
>> a = zeros(1, 2);
>> a(1) = line([1 2], [1 2]);
a =
175.0010 0
>> ishandle(a)
ans =
1 1
Is there a way to check if a handle is valid that will return 0 for non-handle objects?
ishandle accepts common numeric values like 0 (=desktop handle) and 1 (= first open figure by default) which are often also valid handles. However, you will still get an error if you try to set to a property that doesn't exist.
To answer your question either place your code within an exception-handling block:
try
set(a,propName,propValue);
catch
% do something useful...
end
or , if you know what type of object you're looking for, replace ishandle(a) with (for example):
ishandle(a) && strcmp(get(a,'type'),'line')
Matlab handles are in fact just double precision numbers. As you use graphics objects (figures, axes, lines etc) Matlab assigns each item a very specific double as a handle.
The ishandle function checks to see if the number passed in is serving as a handle to any object which can be represented by a handle.
To demonstrate using figures (which are always assigned integer valued doubles):
>> close all; %Close any open figures
>> ishandle(1) %Now the value 1 is not a handle
ans =
0
>> figure(1) %Open a figure, assign it the value 1
>> ishandle(1) %Now 1 i a handle
ans =
1
In your example above, the value 0 is always a handle, representing the Matlab root handle object. This is where some settings related to the command window are held, and it serves as the parent of all figures. The value 175.xxxx is the handles assigned to the line you drew using the plot command.
One useful trick is the findobj function. It finds all objects which are children of a given object, with parameters matching the input parameters. For example:
h = findobj(0,'type','figure'); Returns all figures
h = findobj(0,'type','line'); Returns all line objects in all figures
h = findobj(1,'type','line'); Returns all line objects in figure 1
h = findobj(1,'type','line','color','r'); Returns all line objects in figure 1 whose color is 'r'.