Create a new variable when conditions are met
14 ビュー (過去 30 日間)
古いコメントを表示
Hello All,
A question from a novice here that has been working on what no doubt many of you will consider a very simple problem - but it still eludes me!
In a nutshell, I am trying to achieve the following:
- write a function that will create a new variable when certain conditions are met when looking at an existing variable
Example
Temp is a matrix (177,2) with varying data. When the function [datagrab] is called, if a number appears in the second column that matches the conditions eg '1' (this is not a simple logical test as other integer numbers could be 2,3,4,5 etc.), then that whole row should be copied to a new variable 'G'. If the datagrab function is called again say using datagrab('2','M') - then all rows of data from temp that have the value 2 in the second column would be written to a new variable called 'M', and so on. I hope that makes sense!
I have been trying to just get it to work with '1' and 'G' for now, and I have this:
function [outindex] = datagrab(1,G)
n = 1;
outarray = [];
for G = length(temp)
if (temp(:,2) == '1'); %eg whatever value set as '1' for now
outarray(n)=G;
n = n+1;
else end
end
end
but its just not working for me. So, if anyone could offer a solution for the whole problem, or just a fix to my code above then I will be most grateful.
Heres hoping!
10B.
4 件のコメント
Walter Roberson
2015 年 9 月 10 日
Some routines calculate the extra variables anyhow and some do not. Mostly if the calculation of the variable is "expensive" then the calculation is skipped.
But that does not have to do with creation of variable names dynamically. Each potential output has a name, either named specifically on the left side of the "=" or as varargout{K} for some K. The variables are in the function workspace. When the function returns and there is an output argument to receive the value, everything except the name is copied over (and the reference count is fixed up if appropriate); if there is no slot to receive the value then it is discarded. Nothing dynamic about that.
採用された回答
Thorsten
2015 年 9 月 9 日
編集済み: Thorsten
2015 年 9 月 9 日
temp = [10 2; 20 2; 30 1; 40 2; 50 1; 60 3];
G = temp(temp(:,2) == 2, :);
M = temp(temp(:,2) == 1, :);
If you like to do it in a function, define
function Y = datagrab(X, ind)
Y = X(X(:,2) == ind, :);
and call it using
G = datagrab(temp, 2);
M = datagrap(temp, 1);
その他の回答 (1 件)
Walter Roberson
2015 年 9 月 10 日
function datagrab(condition, varname)
temp = .... some way of getting in the matrix
find some matches and put their indexes into idx
selected = temp(idx,:);
assignin('caller', varname, selected)
end
参考
カテゴリ
Help Center および File Exchange で Whos についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!